Take this code:

$a = 10;
$b = $a;
$a = $a + 1;

It will come as no surprise that $a takes on the value of 11 and that the value of $b stays at 10. If we would like to have $b as a reference to $a then pass $b as reference to $a:

$a = 10;
$b = &$a;
$a = $a + 1;

Note the ampersand prefix. Now $a and $b both have the value of 11.

Compare this to this piece of code:

class A {
    public $return = 0;
    function addOne($val){
        $this->return = $val + 1;
    }
}
$objA = new A;
$objB = $objA;
$objA->addOne(10);
$a = $objA->return;
$b = $objB->return;

$a and $b now both have the value of 11 because both $objA and $objB refer to the same object. Not to your liking? Make $objB a clone of $objA.

class A {
    public $return = 0;
    function addOne($val){
        $this->return = $val + 1;
    }
}
$objA = new A;
$objB = clone $objA;
$objA->addOne(10);
$a = $objA->return;
$b = $objB->return;

Note the “clone” keyword. Now $a has the value of 11 and $b stays at 0.

Sometimes it works like that.

Advertisements