I know this is covered in the php docs but I got confused with this issue .
From the php docs :
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
The above example will output:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
OK so I see that $assigned
survived the original object ($instance
) being assigned to null
, so obviously $assigned
isn't a reference but a copy of $instance.
So what is the difference between
$assigned = $instance
and
$assigned = clone $instance
Objects are abstract data in memory. A variable always holds a reference to this data in memory. Imagine that
$foo = new Bar
creates an object instance ofBar
somewhere in memory, assigns it some id#42
, and$foo
now holds this#42
as reference to this object. Assigning this reference to other variables by reference or normally works the same as with any other values. Many variables can hold a copy of this reference, but all point to the same object.clone
explicitly creates a copy of the object itself, not just of the reference that points to the object.Just don't confuse "reference" as in
=&
with "reference" as in object identifier.