I've been working with PHP5 since it's release and find it very hard to believe I haven't come across this yet. By default, in PHP5, assigning an object instance to another variable, the new variable will access the same instance, but not by reference? To quote the manual:
When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it.
Hence the code... <?php
class MyClass { var $myVariable = '1'; }
$instance1 = new MyClass(); $assignNormally = $instance1; $assignByReference = &$instance1; $clone = clone($instance1);
$assignNormally->myVariable = '2'; $clone->myVariable = 'clone';
var_dump($instance1); // 2 var_dump($assignNormally); // 2 var_dump($assignByReference); // 2 var_dump($clone); // clone
$instance1 = null;
var_dump($instance1); // NULL var_dump($assignNormally); // 2 var_dump($assignByReference); // NULL var_dump($clone); // clone
?>
Produces ...
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
object(MyClass)#2 (1) {
["myVariable"]=>
string(5) "clone"
}
NULL
object(MyClass)#1 (1) {
["myVariable"]=>
string(1) "2"
}
NULL
object(MyClass)#2 (1) {
["myVariable"]=>
string(5) "clone"
}
Had me puzzled at work for quite some time and I ended up searching the Bug reports.