开发者

php __clone() and the "shallow clone"

开发者 https://www.devze.com 2023-02-28 23:02 出处:网络
Wh开发者_如何学Pythonat is meant when the results of __clone() is a \"Shallow Clone\"?This means that when the object is cloned, any properties that are reference variables (variables that refer to ot

Wh开发者_如何学Pythonat is meant when the results of __clone() is a "Shallow Clone"?


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.


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
}
0

精彩评论

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

关注公众号