In PHP objects are automatically passed by reference:
$obj1 = new stdClass();
$obj1->foo = 'bar';
$obj2 = $obj1;
$obj2->foo = 'OOF';
var_dump($obj1->foo); // OOF
Is there an elegant way to copy that variable and NOT refer to the original variable? I want to store a copy of an object and then modify it without effecting the original. Thanks.
You can clone the object:
$obj2 = clone $obj1;
Note that $obj2
will be a shallow copy of $obj1
. As stated in the PHP manual:
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.
You can override the __clone()
method to manually clone any subobjects if you wish.
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