Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop new object from updating with old object's variables

I'm trying to do something like:

$obj2 = $obj1

where $var1 is an object, the problem is that I want $obj2 to be like a snap shot of $obj1 - exactly how it is at that moment, but as $obj1's variables change, $obj2's change as well. Is this even possible? Or am I going to have to create a new "dummy" class just so I can create a clone?

like image 439
jreed121 Avatar asked Feb 24 '23 13:02

jreed121


2 Answers

Simply clone the object, like so:

$obj2 = clone $obj1;

Any modifications to the members of $obj1 after the above statement will not be reflected in $obj2.

like image 127
Tim Cooper Avatar answered Mar 04 '23 04:03

Tim Cooper


Objects are passed by reference in PHP. This means that when you assign an object to new variable, that new variable contains a reference to the same object, NOT a new copy of the object. This rule applies when assigning variables, passing variables into methods, and passing variables into functions.

In your case, both $obj1 and $obj2 reference the same object, so modifying either one will modify the same object.

like image 42
Michael Avatar answered Mar 04 '23 03:03

Michael