Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning objects that contain objects

Tags:

php

Because PHP passes objects by reference by default I've run into a little problem that the follow script demos:

$a = new stdClass();
$a->b = new stdClass();
$a->b->c = 1;

$d = clone $a;

$a->b->c = 10;

print_r($a);
print_r($d);

Is there a way to clone a stdClass and also clone any objects that it might contain? I understand I can use the __clone method to prevent this behavior, but my object is being built via json_decode.

like image 756
Steven Zurek Avatar asked Aug 28 '26 21:08

Steven Zurek


2 Answers

I believe the accepted way is to serialize and unserialize the composite object

$d = unserialize(serialize($a));
like image 179
Crisp Avatar answered Aug 30 '26 12:08

Crisp


Since you already have the JSON, why don't you just create all your objects directly from the JSON

Another hacky way to "deep clone" (i.e. by not adding __clone() methods to the objects) would also be to do:

$object_b = unserialize(serialize($object_a));

Or, since you are dealing all with stdClass objects that are nested:

$object_b = json_decode(json_encode($object_a));
like image 32
Mike Brant Avatar answered Aug 30 '26 11:08

Mike Brant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!