Stop new object from updating using old object variables

I am trying to do something like:

$obj2 = $obj1 

where $ var1 is an object, the problem is that I want $ obj2 to be a snap snapshot of $ obj1 - exactly the same as at the moment, but as $ obj1 changes, $ obj2 also changes. Is it possible? Or do I need to create a new "dummy" class so that I can create a clone?

+4
source share
2 answers

Just clone the object like this:

 $obj2 = clone $obj1; 

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

+7
source

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

In your case, both $obj1 and $obj2 refer to the same object, so changing one of them will change the same object.

+1
source

Source: https://habr.com/ru/post/1347598/


All Articles