Home  >  Article  >  Backend Development  >  php5 object copy, clone, shallow copy and deep copy

php5 object copy, clone, shallow copy and deep copy

WBOY
WBOYOriginal
2016-07-25 08:42:11867browse
The origin of object copy
Why objects have the concept of "copying"? This is closely related to the way objects are passed by value in PHP5. Let's take a look at the following simple code

php code

* /**
* * TV
**/
* class Television
* {
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
* }
*
* $tv1 = new Television();
* $tv2 = $tv1;


This code defines a television class Television, $tv1 is an instance of a television, and then we assign the value of $tv1 to $t2 according to the ordinary variable assignment method. So now we have two TVs $tv1 and $tv2. Is this really the case? Let's test it out.

PHP code

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
* echo
'
';

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
* echo
'
';

*
* //Paint tv2 white
* $tv2->setColor('white');
*
* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
* echo
'
';

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is white


First we see that the colors of tv1 and tv2 are both black. Now we want tv2 to change its color, so we set its color to white. Let’s look at the color of tv2 again. It has indeed become white, which seems to satisfy our needs. However, it did not go as smoothly as expected. When we looked at the color of tv1, we found that tv1 also changed from black to white. We did not reset the color of tv1. Why did tv1 change black to white? This is because the assignment and value transfer of objects in PHP5 are all done by "reference". PHP5 uses Zend Engine II, and objects are stored in a separate structure Object Store, instead of being stored in Zval like other general variables (in PHP4, objects are stored in Zval like general variables). Only the pointer to the object is stored in Zval rather than the content (value). When we copy an object or pass an object as a parameter to a function, we do not need to copy the data. Just keep the same object pointer and notify the Object Store that this particular object now points to via another zval. Since the object itself is located in the Object Store, any changes we make to it will affect all zval structures holding pointers to the object - manifested in the program as any changes to the target object will affect the source object. .This makes it look like PHP objects are always passed by reference. So the above tv2 and tv1 actually point to the same TV instance, and the operations we do on tv1 or tv2 are actually for this same instance. So our "copy" failed.It seems that direct variable assignment cannot copy objects. For this reason, PHP5 provides an operation specifically for copying objects, which is clone. This is where object copying comes in.


Use clone to copy objects
We now use PHP5’s clone language structure to copy objects, the code is as follows:
[size=+0]PHP code

* [size=+0]$tv1 = new Television();
* $tv2 = clone $tv1;
*

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
* echo
'
';

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
* echo
'
';

*

* //Replace tv2 and paint it white
* $tv2->setColor('white');
*

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
* echo
'
';

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black


In the second line of this code, we use the clone keyword to copy tv1. Now we have a real copy of tv1, tv2. We still follow the previous method to check whether the copy is successful. We can see that we changed the color of tv2 to white, and the color of tv1 is still black, so our copy operation is successful.



__clone magic method

Now we consider the situation that each TV should have its own number. This number should be unique like our ID number, so when we copy a TV, we don’t want This number is also copied to avoid causing some trouble. One strategy we came up with is to clear the assigned TV numbers, and then reassign the numbers as needed.
Then the __clone magic method is specifically used to solve such problems. The __clone magic method will be triggered when the object is copied (that is, the clone operation). We modified the code of the TV class Television and added the number attribute and __clone method. The code is as follows.
PHP代码

* /**
* * TV
**/
* class Television
* {
*
* /**
* * TV number
**/
* protected
$_identity = 0;
*
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
*
* /**
* * Return TV number
**/
* public
function getIdentity()
* {
* return
$this->_identity;
* }
*
* /**
* * Set TV number
**/
* public
function setIdentity($id)
* {
* $this->_identity = (int)$id;
* return
$this;
* }
*
* public
function __clone()
* {
* $this->setIdentity(0);
* }
* }


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

PHP代码

* $tv1 = new Television();
* $tv1->setIdentity('111111');
* echo
'id of tv1 is ' . $tv1->getIdentity();//111111
* echo
'
';

*
* $tv2 = clone $tv1;
* echo
'id of tv2 is ' . $tv2->getIdentity();//0


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

clone操作的致命缺陷
clone真的能够达到理想的复制效果吗?在某些情况下,你应该会发现,clone操作并没有我们想象中的那么完美。我们将以上的电视机类修改一下,然后做测试。
每台电视机都会附带一个遥控器,所以我们将会有一个遥控器类,遥控器和电视机是一种“聚合”关系(相对与“组合”关系,是一种较弱的依赖关系,因为一般情况电视机就算没有遥控也能正常使用),现在我们的电视机对象应该都持有一个到遥控器对象的引用。Take a look at the code below
PHP code

* /**
* * TV
**/
* class Television
* {
*
* /**
* * TV number
**/
* protected
$_identity = 0;
*
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Remote control object
**/
* protected
$_control = null;
*
* /**
* * Load the remote control object in the constructor
**/
* public
function __construct()
* {
* $this->setControl(new Telecontrol());
* }
*
* /**
* * Set remote control object
**/
* public
function setControl(Telecontrol $control)
* {
* $this->_control = $control;
* return
$this;
* }
*
* /**
* * Returns the remote control object
**/
* public
function getControl()
* {
* return
$this->_control;
* }
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
*
* /**
* * Return TV number
**/
* public
function getIdentity()
* {
* return
$this->_identity;
* }
*
* /**
* * Set TV number
**/
* public
function setIdentity($id)
* {
* $this->_identity = (int)$id;
* return
$this;
* }
*
* public
function __clone()
* {
* $this->setIdentity(0);
* }
* }
*
*
* /**
* * Remote control category
**/
* class Telecontrol
* {
*
* }


Copy such a TV object below and observe the remote control object of the TV.

PHP code

* $tv1 = new Television();
* $tv2 = clone $tv1;
*
* $contr1 = $tv1->getControl(); //Get the remote control contr1 of tv1
* $contr2 = $tv2->getControl(); //Get the remote control contr2 of tv2
* echo
$tv1; //The object id of tv1 is #1
* echo
'
';

* echo
$contr1; //The object id of contr1 is #2
* echo
'
';

* echo
$tv2; //The object id of tv2 is #3
* echo
'
';

* echo
$contr2; //The object id of contr2 is #2


After copying, we check the object ID and copy tv2 from tv1 through the clone operation. The object IDs of tv1 and tv2 are 1 and 3 respectively. This means that tv1 and tv2 refer to two different TV objects, which is consistent with clone. The result of the operation. Then we obtained the remote control object contr1 of tv1 and the remote control object contr2 of tv2 respectively. By looking at their object IDs, we found that the object IDs of contr1 and contr2 are both 2, which indicates that they are references to the same object, that is It is obviously unreasonable to say that although we have copied tv2 from tv1, the remote control has not been copied. Each TV should be equipped with a remote control, and here tv2 and tv1 share a remote control.

It can be seen that the clone operation has such a big flaw: when using the clone operation to copy an object, when the copied object has references to other objects, the referenced objects will not be copied. However, this situation is very common. Nowadays, "synthesis/aggregation reuse" is mostly advocated to replace "inheritance reuse". "Synthesis" and "aggregation" are to let one object have a reference to another object, thereby reusing it. Use the method of the referenced object. We should consider this situation when using clone. So how should we solve such a defect when cloning an object? Maybe you quickly thought of the __clone magic method mentioned earlier, which is indeed a solution.

Option 1: Use __clone magic method to make up for it
We have already introduced the use of the __clone magic method. We can re-reference the references of other objects in the copied object to a new object in the __clone method. Let’s take a look at the modified __clone() magic method:

[size=+0][size=+0]PHP code

* [size=+0][size=+0]public
function __clone()
* {
* $this->setIdentity(0);
* //Reset a remote control object
* $this->setControl(new Telecontrol());
* }


In line 04, we reset a remote control for the copied TV object. We check the object ID according to the previous method and can find that the remote controls of the two TVs have different object IDs, so our problem is solved.

But this method is probably not very good. If the copied object has multiple references to other objects, we must reset them one by one in the __clone method. What’s worse is if the class of the copied object is changed by If provided by a third party, we cannot modify the code, so the copy operation will basically not be completed smoothly.
We use clone to copy objects. This kind of copy is called "shallow copy": all variables of the copied object contain the same values ​​as the original object, and all references to other objects still point to the original object. That is, a shallow copy only copies the object in question, not the objects it refers to. Compared with "shallow copy", of course there is also a "deep copy": all variables of the copied object contain the same values ​​as the original object, except those variables that refer to other objects. In other words, deep copy copies all the objects referenced by the object to be copied. Deep copying requires deciding how deep to go, which is a problem that is not easy to determine. In addition, circular reference problems may occur, which must be handled carefully. Our option 2 will be a deep copy solution.

Option 2: Use serialization for deep copy
PHP has serialize and unserialize functions. We only need to use serialize() to write an object to a stream, and then read the object back from the stream, then the object will be copied. In the Java language, this process is called "refrigeration" and "thawing". Below we will test this method:
[size=+0][size=+0]PHP code

* [size=+0][size=+0]$tv1 = new Television();
* $tv2 = unserialize(serialize($tv1));//Serialize and then deserialize
*

* $contr1 = $tv1->getControl(); //Get the remote control contr1 of tv1
* $contr2 = $tv2->getControl(); //Get the remote control contr2 of tv2
*

* echo
$tv1; //The object id of tv1 is #1
* echo
'
';

* echo
$contr1; //The object id of contr1 is #2
* echo
'
';

* echo
$tv2; //The object id of tv2 is #4
* echo
'
';

* echo
$contr2; //The object id of contr2 is #5


We can see the output, tv1 and tv2 have different remote controls. This is much more convenient than Option 1. Serialization is a recursive process. We don't need to care about how many objects are referenced within the object and how many layers of objects are referenced. We can completely copy it. Note that when using this solution, we cannot trigger the __clone magic method to complete some additional operations. Of course, we can perform a clone operation again after deep copying to trigger the __clone magic method, but it will have a small impact on efficiency. In addition, this solution will trigger the __sleep and __wakeup magic methods of the copied object and all referenced objects, so these situations need to be considered.



Summary
Different object copying methods have different effects. We should consider which method to use and how to improve the copying method based on specific application requirements. The object-oriented features of PHP5 are relatively close to JAVA. I believe we can learn a lot of valuable experience from JAVA.
clone


Statement:
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