I was tested and I got this wrong but this doesn’t make sense:
class myClass
{
public $x;
function myMethod()
{
echo $this->x;
}
}
$a = new myClass();
$a->x = 10;
$b = $a;
$b->x = 20;
$c = clone $b;
$c->x = 30;
$a->myMethod();
$b->myMethod();
$c->myMethod();
My intuition would be 102030 but the result is actually 202030!!! What happened to 10?!?! Shouldn’t the variable of $a be left alone? I thought all objects are independent and would not be updated unless it has direct reference set by the ampersand (=&)?
In
$b = $a;, only the object reference is being copied, not the object.When you use
clone, however, the object is indeed being copied, so$c = clone $b,creates both a new object (referenced by$c) and a new reference ($c).In
$b =& $a;, both symbols$aand$bwould point to the same reference, that is, not even the reference would be copied (and therefore an assignment to$bof, say, an integer, would also affect the value of$a).To sum up, there are two indirections here: from the symbol to the “zval” (in the case an object reference) and from the object reference to the object itself (i.e., to a portion of memory where the actual object state is stored).