MrAsk
MrAsk

Reputation: 25

PHP objects in array copy

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!

Upvotes: 2

Views: 127

Answers (3)

Pierrickouw
Pierrickouw

Reputation: 4704

Try to use clone want you work with object.

Someone wrote a function for that, when objects are in array.

Here the link

Upvotes: 0

Arjen
Arjen

Reputation: 396

Objects are passed by reference in php5 (wich is usually how you would want your objects passed), arrays are not.

Use clone http://php.net/manual/en/language.oop5.cloning.php

--edit just a sec too late :-) --

Upvotes: 0

Marius Balčytis
Marius Balčytis

Reputation: 2651

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.

When assigning an already created instance of a class 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 copy of an already created object can be made by cloning it.

From http://php.net/manual/en/language.oop5.basic.php

So, you need to call clone if you want another object.

$array4['john'] = clone $array3['john'];

Upvotes: 4

Related Questions