Home php教程 php手册 深入讨论PHP5对象复制技术

深入讨论PHP5对象复制技术

Jun 13, 2016 am 10:45 AM
php5 copy object technology go deep of discuss

 

 

此文将由浅入深的讨论PHP5的对象复制技术  原创文章 请尊重版权  有错误或则不当之处还希望能够指出来

对象复制的由来

为什么对象会有“复制”这个概念,这与PHP5中对象的传值方式是密切相关的,让我们看看下面这段简单的代码

 

PHP代码

 

 

  1. /** 
  2.  * 电视机类 
  3.  */  
  4. class Television   
  5. {  
  6.     /** 
  7.      * 屏幕高度 
  8.      */  
  9.     protected $_screenLength = 300;  
  10.       
  11.     /** 
  12.      * 屏幕宽度 
  13.      */  
  14.     protected $_screenHight  = 200;  
  15.       
  16.     /** 
  17.      * 电视机外观颜色 
  18.      */  
  19.     protected $_color        = 'black';  
  20.       
  21.     /** 
  22.      * 返回电视外观颜色 
  23.      */  
  24.     public function getColor()  
  25.     {  
  26.         return $this->_color;  
  27.     }  
  28.       
  29.     /** 
  30.      * 设置电视机外观颜色 
  31.      */  
  32.     public function setColor($color)  
  33.     {  
  34.         $this->_color = (string)$color;  
  35.         return $this;  
  36.     }  
  37. }  
  38.   
  39. $tv1 = new Television();  
  40. $tv2 = $tv1;  

 

这段代码定义了一个电视机的类 Television , $tv1为一个电视机的实例,然后我们按照普通的变量赋值方式将$tv1的值赋给$t2。那么现在我们拥有两台电视机$tv1和$tv2了,真的是这样的吗?我们来测试一下。

 

PHP代码

 

 

  1. echo 'color of tv1 is: ' . $tv1->getColor();//tv1的颜色是black  
  2. echo '
    ';  
  3. echo 'color of tv2 is: ' . $tv2->getColor();//tv2的颜色是black  
  4. echo '
    ';  
  5.   
  6. //把tv2涂成白色  
  7. $tv2->setColor('white');  
  8.   
  9. echo 'color of tv2 is: ' . $tv2->getColor();//tv2的颜色是white  
  10. echo '
    ';  
  11. echo 'color of tv1 is: ' . $tv1->getColor();//tv1的颜色是white  

 

 首先我们看到tv1和tv2的颜色都是black,现在我们希望tv2换个颜色,所以我们将它的颜色设置成了white,我们再看看tv2的颜色,确实成为了white,似乎满足了我们的要求,可是并没有想象中的那么顺利,当我们接着看tv1的颜色的时候,我们发现tv1也由black边成了white。我们并没有重新设置tv1的颜色,为什么tv1会重black变成white呢?这是因为PHP5中对象的赋值和传值都是以“引用”的方式。PHP5使用了Zend引擎II,对象被储存于独立的结构Object Store中,而不像其它一般变量那样储存于Zval中(在PHP4中对象和一般变量一样存储于Zval)。在Zval中仅存储对象的指针而不是内容(value)。当我们复制一个对象或者将一个对象当作参数传递给一个函数时,我们不需要复制数据。仅仅保持相同的对象指针并由另一个zval通知现在这个特定的对象指向的Object Store。由于对象本身位于Object Store,我们对它所作的任何改变将影响到所有持有该对象指针的zval结构----表现在程序中就是目标对象的任何改变都会影响到源对象。.这使PHP对象看起来就像总是通过引用(reference)来传递。所以以上的tv2和tv1其实是指向同一个电视机实例,我们对tv1或则tv2所做的操作其实都是针对这同一个实例。因此我们的“复制”失败了。看来直接变量赋值的方式并不能拷贝对象,为此PHP5提供了一个专门用于复制对象的操作,也就是 clone 。这就是对象复制的由来。

用clone(克隆)来复制对象

我们现在使用PHP5的clone语言结构来复制对象,代码如下:

PHP代码

 

  1. $tv1 = new Television();  
  2. $tv2 = clone $tv1;  
  3.   
  4. echo 'color of tv1 is: ' . $tv1->getColor();//tv1的颜色是black  
  5. echo '
    ';  
  6. echo 'color of tv2 is: ' . $tv2->getColor();//tv2的颜色是black  
  7. echo '
    ';  
  8.   
  9. //把tv2换成涂成白色  
  10. $tv2->setColor('white');  
  11.   
  12. echo 'color of tv2 is: ' . $tv2->getColor();//tv2的颜色是white  
  13. echo '
    ';  
  14. echo 'color of tv1 is: ' . $tv1->getColor();//tv1的颜色是black  

 

这段代码的第2行,我们用clone关键字复制tv1,现在我们就拥有了一份真正的tv1的拷贝tv2,我们还是按照之前的方法来检测复制是否成功。我们可以看到,我们将tv2的颜色换成了white,tv1的颜色还是black,这样我们的复制操作就成功了。

__clone魔术方法

    现在我们考虑到这样一个情况,每一台电视机应该都有自己的编号,这个编号如同我们的身份证号码一样应该是唯一的,所以当我们在复制一台电视机的时候,我们不希望这个编号也被复制过来,以免造成一些麻烦。我们想到的一个策略是将赋值出来的电视机的编号清空,然后再按照需求来重新分配编号。

    那么__clone魔术方法就是专门用来解决这样的问题,__clone魔术方法会在对象被复制( 也就是clone操作)的时候被触发。我们修改了电视机类Television的代码,添加了编号属性和__clone方法,代码如下。

PHP代码

 

 

  1. /** 
  2.  * 电视机类 
  3.  */  
  4. class Television   
  5. {  
  6.       
  7.     /** 
  8.      * 电视机编号 
  9.      */  
  10.     protected $_identity    = 0;  
  11.       
  12.     /** 
  13.      * 屏幕高度 
  14.      */  
  15.     protected $_screenLength = 300;  
  16.       
  17.     /** 
  18.      * 屏幕宽度 
  19.      */  
  20.     protected $_screenHight  = 200;  
  21.       
  22.     /** 
  23.      * 电视机外观颜色 
  24.      */  
  25.     protected $_color        = 'black';  
  26.       
  27.     /** 
  28.      * 返回电视外观颜色 
  29.      */  
  30.     public function getColor()  
  31.     {  
  32.         return $this->_color;  
  33.     }  
  34.       
  35.     /** 
  36.      * 设置电视机外观颜色 
  37.      */  
  38.     public function setColor($color)  
  39.     {  
  40.         $this->_color = (string)$color;  
  41.         return $this;  
  42.     }  
  43.   
  44.    /** 
  45.      * 返回电视机编号 
  46.      */  
  47.     public function getIdentity()  
  48.     {  
  49.         return $this->_identity;      
  50.     }  
  51.       
  52.     /** 
  53.      * 设置电视机编号 
  54.      */  
  55.     public function setIdentity($id)  
  56.     {  
  57.         $this->_identity = (int)$id;  
  58.         return $this;  
  59.     }  
  60.       
  61.     public function __clone()  
  62.     {  
  63.         $this->setIdentity(0);    
  64.     }  
  65. }  

 

下面我们来复制这样的一个电视机对象。

 

PHP代码

 

  1. $tv1 = new Television();  
  2. $tv1->setIdentity('111111');  
  3. echo 'id of tv1 is ' . $tv1->getIdentity();//111111  
  4. echo '
    ';  
  5.   
  6. $tv2 = clone $tv1;  
  7. echo 'id of tv2 is ' . $tv2->getIdentity();//0  

 

我们生产了一台电视机tv1 , 并且设置它的编号为111111,然后我们用clone将tv1复制得到了tv2,这个时候__clone魔术方法被触发,此方法将直接作用与复制得到的对象tv2,我们在__clone方法中调用了setIdentity成员方法将tv2的_identity属性清空,以便我们后面对它进行重新编号。由此我们可以看到__clone魔术方法能让我们非常方便的在clone对象的时候做一些附加的操作。

clone操作的致命缺陷

    clone真的能够达到理想的复制效果吗?在某些情况下,你应该会发现,clone操作并没有我们想象中的那么完美。我们将以上的电视机类修改一下,然后做测试。

    每台电视机都会附带一个遥控器,所以我们将会有一个遥控器类,遥控器和电视机是一种“聚合”关系(相对与“组合”关系,是一种较弱的依赖关系,因为一般情况电视机就算没有遥控也能正常使用),现在我们的电视机对象应该都持有一个到遥控器对象的引用。下面看看代码

PHP代码

 

 

  1. /** 
  2.  * 电视机类 
  3.  */  
  4. class Television   
  5. {  
  6.       
  7.     /** 
  8.      * 电视机编号 
  9.      */  
  10.     protected $_identity    = 0;  
  11.       
  12.     /** 
  13.      * 屏幕高度 
  14.      */  
  15.     protected $_screenLength = 300;  
  16.       
  17.     /** 
  18.      * 屏幕宽度 
  19.      */  
  20.     protected $_screenHight  = 200;  
  21.       
  22.     /** 
  23.      * 电视机外观颜色 
  24.      */  
  25.     protected $_color        = 'black';  
  26.       
  27.     /** 
  28.      * 遥控器对象 
  29.      */  
  30.     protected $_control      = null;  
  31.       
  32.     /** 
  33.      * 构造函数中加载遥控器对象 
  34.      */  
  35.     public function __construct()  
  36.     {  
  37.         $this->setControl(new Telecontrol());  
  38.     }  
  39.   
  40.     /** 
  41.      * 设置遥控器对象 
  42.      */  
  43.     public function setControl(Telecontrol $control)  
  44.     {  
  45.         $this->_control = $control;  
  46.         return $this;  
  47.     }  
  48.       
  49.     /** 
  50.      * 返回遥控器对象 
  51.      */  
  52.     public function getControl()  
  53.     {  
  54.         return $this->_control;  
  55.     }      
  56.       
  57.     /** 
  58.      * 返回电视外观颜色 
  59.      */  
  60.     public function getColor()  
  61.     {  
  62.         return $this->_color;  
  63.     }  
  64.       
  65.     /** 
  66.      * 设置电视机外观颜色 
  67.      */  
  68.     public function setColor($color)  
  69.     {  
  70.         $this->_color = (string)$color;  
  71.         return $this;  
  72.     }  
  73.   
  74.    /** 
  75.      * 返回电视机编号 
  76.      */  
  77.     public function getIdentity()  
  78.     {  
  79.         return $this->_identity;      
  80.     }  
  81.       
  82.     /** 
  83.      * 设置电视机编号 
  84.      */  
  85.     public function setIdentity($id)  
  86.     {  
  87.         $this->_identity = (int)$id;  
  88.         return $this;  
  89.     }  
  90.       
  91.     public function __clone()  
  92.     {  
  93.         $this->setIdentity(0);    
  94.     }  
  95. }  
  96.   
  97.   
  98. /** 
  99.  * 遥控器类 
  100.  */  
  101. class Telecontrol   
  102. {  
  103.   
  104. }  

 

下面复制这样的一个电视机对象并且观察电视机的遥控器对象。

 

PHP代码

 

  1. $tv1 = new Television();  
  2. $tv2 = clone $tv1;  
  3.   
  4. $contr1 = $tv1->getControl(); //获取tv1的遥控器contr1  
  5. $contr2 = $tv2->getControl(); //获取tv2的遥控器contr2  
  6. echo $tv1;    //tv1的object id 为 #1  
  7. echo '
    ';  
  8. echo $contr1; //contr1的object id 为#2  
  9. echo '
    ';   
  10. echo $tv2;    //tv2的object id 为 #3  
  11. echo '
    ';  
  12. echo $contr2; //contr2的object id 为#2  

 

经过复制之后,我们查看对象id,通过clone操作从tv1复制出了tv2,tv1和tv2的对象id分别是1和3,这表示tv1和tv2是引用两个不同的电视机对象,这符合clone操作的结果。然后我们分别获取了tv1的遥控器对象contr1和tv2的遥控器对象contr2,通过查看它们的对象id我们发现contr1和contr2的对象id都是2,这表明它们是到同一个对象的引用,也就是说我们虽然从tv1复制出tv2,但是遥控器并没有被复制,每台电视机都应该配有一个遥控器,而这里tv2和tv1共用一个遥控器,这显然是不合常理的。

    由此可见,clone操作有这么一个非常大的缺陷:使用clone操作复制对象时,当被复制的对象有对其它对象的引用的时候,引用的对象将不会被复制。然而这种情况又非常的普遍,现今 “合成/聚合复用”多被提倡用来代替“继承复用”,“合成”和“聚合”就是让一个对象拥有对另一个对象的引用,从而复用被引用对象的方法。我们在使用clone的时候应该考虑到这样的情况。那么在clone对象的时候我们应该如何去解决这样的一个缺陷呢?可能你很快就想到了之前提到的__clone魔术方法,这确实是一种解决方案。

方案1:用__clone魔术方法弥补

    前面我们已经介绍了__clone魔术方法的用法,我们可以在__clone方法中将被复制对象中其它对象的引用重新引用到一个新的对象。下面我们看看修改后的__clone()魔术方法:

 

PHP代码

 

 

  1. public function __clone()  
  2. {  
  3.     $this->setIdentity(0);  
  4.     //重新设置一个遥控器对象  
  5.     $this->setControl(new Telecontrol());  
  6. }  

 

第04行中我们为复制出来的电视机对象重新设置了一个遥控器,我们按照之前的方法查看对象的id可以发现,两台电视机的遥控器拥有不同的对象id,这样我们的问题就解决了。

但是这样的方式大概并不算太好,如果被复制对象中有多个到其它对象的引用,我们必须在__clone方法中逐个的重新设置,更糟糕的是如果被复制对象的类由第三方提供,我们无法修改代码,那复制操作基本就无法顺利完成了。

我们使用clone来复制对象,这种复制叫做“浅复制”:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象。也就是说,浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。相对于“浅复制”,当然也有一个“深复制”:被复制的对象的所有的变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。也就是说,深复制把要复制的对象所引用的对象都复制了一遍。深复制需要决定深入到多少层,这是一个不容易确定的问题,此外可能会出现循环引用的问题,这些都必须小心处理。我们的方案2将是一个深复制的解决方案。

方案2:利用串行化做深复制

PHP有串行化(serialize)和反串行化(unserialize)函数,我们只需要用serialize()将一个对象写入一个流,然后从流中读回对象,那么对象就被复制了。在JAVA语言里面,这个过程叫做“冷藏”和“解冻”。下面我们将测试一下这个方法:

PHP代码

 

  1. $tv1 = new Television();  
  2. $tv2 = unserialize(serialize($tv1));//序列化然后反序列化  
  3.   
  4. $contr1 = $tv1->getControl(); //获取tv1的遥控器contr1  
  5. $contr2 = $tv2->getControl(); //获取tv2的遥控器contr2  
  6.   
  7. echo $tv1;    //tv1的object id 为 #1  
  8. echo '
    ';  
  9. echo $contr1; //contr1的object id 为#2  
  10. echo '
    ';   
  11. echo $tv2;    //tv2的object id 为 #4  
  12. echo '
    ';  
  13. echo $contr2; //contr2的object id 为#5  

 

我们可以看到输出结果,tv1和tv2拥有了不同的遥控器。这比方案1要方便很多,序列化是一个递归的过程,我们不需要理会被对象内部引用了多少个对象以及引用了多少层对象,我们都可以彻底的复制。注意使用此方案时我们无法触发__clone魔术方法来完成一些附加操作,当然我们可以在深复制之后再进行一次clone操作来触发__clone魔术方法,只是会对效率些小的影响。另外此方案会触发被复制对象和所有被引用对象的__sleep和__wakeup魔术方法,所以这些情况都需要被考虑。

总结

   不同的对象复制方式有着不同的效果,我们应该根据具体应用需求来考虑使用哪种方式以及如何改进复制方式。PHP5的面向对象特性和JAVA比较接近,相信我们可以从JAVA中借鉴很多宝贵的经验

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to copy lyrics from QQ Music How to copy lyrics How to copy lyrics from QQ Music How to copy lyrics Mar 12, 2024 pm 08:22 PM

We users should be able to understand the diversity of some functions when using this platform. We know that the lyrics of some songs are very well written. Sometimes we even listen to it several times and feel that the meaning is very profound. So if we want to understand the meaning of it, we want to copy it directly and use it as copywriting. However, if we want to use it, we still need to You just need to learn how to copy lyrics. I believe that everyone is familiar with these operations, but it is indeed a bit difficult to operate on a mobile phone. So in order to give you a better understanding, today the editor is here to help you. A good explanation of some of the above operating experiences. If you also like it, come and take a look with the editor. Don’t miss it.​

The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? The Stable Diffusion 3 paper is finally released, and the architectural details are revealed. Will it help to reproduce Sora? Mar 06, 2024 pm 05:34 PM

StableDiffusion3’s paper is finally here! This model was released two weeks ago and uses the same DiT (DiffusionTransformer) architecture as Sora. It caused quite a stir once it was released. Compared with the previous version, the quality of the images generated by StableDiffusion3 has been significantly improved. It now supports multi-theme prompts, and the text writing effect has also been improved, and garbled characters no longer appear. StabilityAI pointed out that StableDiffusion3 is a series of models with parameter sizes ranging from 800M to 8B. This parameter range means that the model can be run directly on many portable devices, significantly reducing the use of AI

DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! DualBEV: significantly surpassing BEVFormer and BEVDet4D, open the book! Mar 21, 2024 pm 05:21 PM

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

This article is enough for you to read about autonomous driving and trajectory prediction! This article is enough for you to read about autonomous driving and trajectory prediction! Feb 28, 2024 pm 07:20 PM

Trajectory prediction plays an important role in autonomous driving. Autonomous driving trajectory prediction refers to predicting the future driving trajectory of the vehicle by analyzing various data during the vehicle's driving process. As the core module of autonomous driving, the quality of trajectory prediction is crucial to downstream planning control. The trajectory prediction task has a rich technology stack and requires familiarity with autonomous driving dynamic/static perception, high-precision maps, lane lines, neural network architecture (CNN&GNN&Transformer) skills, etc. It is very difficult to get started! Many fans hope to get started with trajectory prediction as soon as possible and avoid pitfalls. Today I will take stock of some common problems and introductory learning methods for trajectory prediction! Introductory related knowledge 1. Are the preview papers in order? A: Look at the survey first, p

Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Apr 18, 2024 pm 09:43 PM

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques Jun 02, 2024 pm 06:57 PM

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

See all articles