Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a PHP object NOT by reference [duplicate]

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.

like image 602
emersonthis Avatar asked Dec 11 '22 15:12

emersonthis


1 Answers

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.

like image 181
Viktor Avatar answered Jan 06 '23 15:01

Viktor