emersonthis emersonthis - 7 months ago 23
PHP Question

How to pass a PHP object NOT by reference

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.