A short test to confirm references are preserved in cloned arrays.
// create a stdClass object (using my lazy way of coercing arrays to objects) $object = (object) array( 'thing' => 'original' ); // add that object to an array element $array = array( 'object_one' => $object ); // clone the array by assignment to a new variable $array_two = $array; // add a new copy of the original object to a new element in the new array $array_two['object_two'] = $object; // show what we have so far var_dump( $object , $array , $array_two );
The result is:
object(stdClass)#1 (1) {
["thing"]=>
string(8) "original"
}
array(1) {
["object_one"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(8) "original"
}
}
array(2) {
["object_one"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(8) "original"
}
["object_two"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(8) "original"
}
}
Now let’s mess with one piece of that to check if the object was passed by reference or got cloned:
// change one of the objects in the second array $array_two['object_two']->thing = 'array_two,object_two'; // see that all the references to that object have been changed var_dump( $object , $array , $array_two );
Confirmed, the object is passed by reference, even though the array that contained it was cloned:
object(stdClass)#1 (1) {
["thing"]=>
string(20) "array_two,object_two"
}
array(1) {
["object_one"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(20) "array_two,object_two"
}
}
array(2) {
["object_one"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(20) "array_two,object_two"
}
["object_two"]=>
object(stdClass)#1 (1) {
["thing"]=>
string(20) "array_two,object_two"
}
}
Recently Commented