好好爱自己!

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 的, 单例对象只允许 有一个对象, 一般不允许存在多个实例。否则就违反了单例这种设计模式的初衷。

1
2
3
4
5
6
7
8
9
/**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

  

posted @   立志做一个好的程序员  阅读(321)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示