开发者

Stop new object from updating with old object's variables

开发者 https://www.devze.com 2023-02-24 11:20 出处:网络
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

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消