php中__clone() shallow copy 只是浅复制

什么是浅复制呢?

简单一点,就是说复制一个对象的时候,如果对象$Obj的一个属性的类型是引用类型的,比如 $person这个属性,指向的是一个 叫做 $objPerson的一个引用, 那么复制$Obj的时候,

新复制出来的 $Obj_copy这个对象 和原来的 $Obj 这个对象的 $person属性,都指向的是同一个对象 $objPerson. 并没有重新开辟内存,生成新的 $objPerson对象。。

这种复制比较简单, 所以就叫做 浅复制 shallow copy..

php __clone() and the “shallow clone”

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.

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.

The clone keyword in PHP represents a shallow copy.

In order to achieve a deep copy, you need to implement the magic method __clone

If you clone an object that has a member which is an object of another class with the simple clonekeyword, you would be keeping the same reference to that second object.

That's where the deep copy comes in handy, with something like this:

public function __clone()
{
    $this->someOtherObject = clone $this->someOtherObject;
}

With that, you guarantee the clone will be deep, meaning it will clone the member objects as well, instead of just keeping the original reference to them.

------------------------------------------------------分割线----------------------------------------------------------

补充: 私有化的 __clone()  , 对于单例的对象是禁止 deep copy 的, 单例对象只允许 有一个对象, 一般不允许存在多个实例。否则就违反了单例这种设计模式的初衷。

/**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

  

原文地址:https://www.cnblogs.com/oxspirt/p/5817004.html