I got a strange behaviour in PHP with arrays and objects, that I don’t understand. Maybe you guys can help me with that.
Creating an array, copy it to another array, change a value in the 2nd array and everything is as expected:
$array1['john']['name'] = 'foo';
$array2 = $array1;
$array2['john']['name'] = 'bar';
echo $array1['john']['name']; // foo
echo $array2['john']['name']; // bar
Now, if I do this with objects in that array, the object in the copied array holds some kind of a reference?
$array3['john']->name = 'foo';
$array4 = $array3;
$array4['john']->name = 'bar';
echo $array3['john']->name; // bar
echo $array4['john']->name; // bar
I would have expected the same behaviour as in the 1st example and I cannot find anything about this in the php docs. Can somebody explain that to me or send me an link to where this is documented?
Thanks!
Objects by default are passed by reference. If you assign some scalar value or an array to other variable, it is cloned. If you assign the object, only the reference is copied but the object is not.
From http://php.net/manual/en/language.oop5.basic.php
So, you need to call
cloneif you want another object.