阻止新对象使用旧对象的变量进行更新
我正在尝试做类似的事情:
$obj2 = $obj1
其中 $var1 是一个对象,问题是我希望 $obj2 就像 $obj1 的快照 - 正是当时的样子,但是随着 $obj1 的变量发生变化,$ obj2 也发生了变化。这可能吗?或者我是否必须创建一个新的“虚拟”类,以便我可以创建一个克隆?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需克隆该对象,如下所示:
在上述语句之后对
$obj1
成员的任何修改都不会反映在$obj2
中。Simply clone the object, like so:
Any modifications to the members of
$obj1
after the above statement will not be reflected in$obj2
.在 PHP 中对象是通过引用传递的。这意味着当您将一个对象分配给新变量时,该新变量包含对同一对象的引用,而不是该对象的新副本。此规则适用于分配变量、将变量传递给方法以及将变量传递给函数时。
在您的情况下,
$obj1
和$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.