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

浅复制与深复制解析
本文详细解释了浅复制的概念,即复制对象时保留原有对象的引用类型不变,仅复制其值类型。并介绍了PHP中如何实现浅复制与深复制的区别,通过__clone()方法实现深复制的过程。

什么是浅复制呢?

简单一点,就是说复制一个对象的时候,如果对象$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()
    {
    }

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值