php __clone() and the “shallow clone”

半腔热情 提交于 2019-12-08 19:30:19

问题


What is meant when the results of __clone() is a "Shallow Clone"?


回答1:


In short: A clone will remain the same references as the original object it is cloned from. Primitive types like strings, or integer are never references (in php) and if you change one reference completely (by replacing the object of a property with another one), this will also not affect the original object. Every property will contain the same and not only the identical object, than the same-named property of the other object.

To create non-swallow copies you must implement __clone(). This is called on the cloned object after the cloning.

public function __clone () {
  $this->myObject = clone $this->myObject;
  // and so on
}



回答2:


This means that when the object is cloned, any properties that are reference variables (variables that refer to other objects, rather than a value) will remain references.

A "non-shallow" clone would set the new object's to the values of those properties, rather than leaving them as references.

Note: This means that any changes you make to those references in the cloned object will also be made to the values they reference in the "parent" object.



来源:https://stackoverflow.com/questions/5809439/php-clone-and-the-shallow-clone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!