tags:

views:

37

answers:

2

I write some code:

class A {

  private $x = 1;
  private $y = "z";

  public function setX($x){
   $this->x = $x;
  }

  public function getX(){
   return $this->x;
  }

 }

 $a1 = new A();

 $a1->setX(2);

 echo $a1->getX();

 $a2 = $a1;

 $a2->setX(666);

 echo $a1->getX();

I have output:

2

666

But I set value "666" only for object $a2.

Why value in $a1 changed too?

(OS: Ubuntu 10.04, PHP 5.3.2-1)

A: 
$a2 = new A();

You need to create new object of class.

Alexander.Plutov
+1  A: 

Objects are passed by reference in contrast to arrays which are passed by value. This is the preferred behaviour in oop languages and is much more flexible than copying everything as soon as it's re-assign to another variable. Copying can be done manually if it is desired.

Willi