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.
I believe the accepted way is to serialize and unserialize the composite object
$d = unserialize(serialize($a));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With