Home  >  Article  >  Backend Development  >  In-depth discussion of PHP5 object copy technology_PHP tutorial

In-depth discussion of PHP5 object copy technology_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:46:41952browse

This article will discuss the object copying technology of PHP5 from the simple to the in-depth. Original article. Please respect the copyright. If there are any errors or inappropriate things, I hope you can point them out

The origin of object copy

Why does an object have the concept of "copying"? This is closely related to the value-passing method of objects in PHP5. Let's take a look at the following simple code

PHP code

  1. /**
  2. * TV type
  3. ​*/
  4. class Television
  5. {
  6. /**
  7. *Screen height
  8. ​​*/
  9. Protected $_screenLength = 300;
  10.          
  11. /**
  12. *Screen width
  13. ​​*/
  14. protected $_screenHight = 200;
  15.          
  16. /**
  17. * TV appearance color
  18. ​​*/
  19. protected $_color = 'black';
  20.          
  21. /**
  22. * Return to TV appearance color
  23. ​​*/
  24. Public function getColor()
  25.                                                                                                                                             using                                                                                              out return $this->_color;                        
  26. }  
  27.          
  28. /**
  29. *Set the appearance color of the TV
  30. ​​*/
  31. Public function setColor($color)
  32.           $this->_color = (string)$color;                                                  
  33.          return $this;                                  
  34. }  
  35. }
  36. $tv1 = new Television();
  37. $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 '
    ';
  1. echo 'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
  2. echo '
    ';
  3. //Paint tv2 white
  4. $tv2->setColor('white');
  5. echo 'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
  6. echo '
    ';
  7. echo 'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is white
  8. 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 meet our requirements. , but it was not as smooth 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 of 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:

    PHP code

    1. $tv1 = new Television();
    2. $tv2 = clone $tv1;
    3. echo 'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
    4. echo '
      ';
    5. echo 'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
    6. echo '
      ';
    7. //Change tv2 and paint it white
    8. $tv2->setColor('white');
    9. echo 'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
    10. echo '
      ';
    11. echo 'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black

    In line 2 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 The number has also been copied to avoid causing some trouble. One strategy we came up with is to clear the assigned TV numbers, and then reassign the numbers according to needs.

    ​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 code

    1. /**
    2. * TV type
    3. ​*/  
    4. class Television   
    5. {  
    6.       
    7.     /**
    8. * TV number
    9. ​​*/  
    10.     protected $_identity    = 0;  
    11.       
    12.     /**
    13. *Screen height
    14. ​​*/  
    15.     protected $_screenLength = 300;  
    16.       
    17.     /**
    18. *Screen width
    19. ​​*/  
    20.     protected $_screenHight  = 200;  
    21.       
    22.     /**
    23. * TV appearance color
    24. ​​*/  
    25.     protected $_color        = 'black';  
    26.       
    27.     /**
    28. * Return to TV appearance color
    29. ​​*/  
    30.     public function getColor()  
    31.     {  
    32.         return $this->_color;  
    33.     }  
    34.       
    35.     /**
    36. *Set the appearance color of the TV
    37. ​​*/  
    38.     public function setColor($color)  
    39.     {  
    40.         $this->_color = (string)$color;  
    41.         return $this;  
    42.     }  
    43.   
    44.    /**
    45. * Return to TV number
    46. ​​*/  
    47.     public function getIdentity()  
    48.     {  
    49.         return $this->_identity;      
    50.     }  
    51.       
    52.     /**
    53. *Set TV number
    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. $tv2 = clone $tv1;
    6. echo 'id of tv2 is ' . $tv2->getIdentity();//0

    We produced a TV set tv1 and set its number to 111111. Then we used clone to copy tv1 to get tv2. At this time, the __clone magic method was triggered. This method will directly act on the copied object tv2. We In the __clone method, the setIdentity member method is called to clear the _identity attribute of tv2 so that we can renumber it later. From this we can see that the __clone magic method allows us to do some additional operations very conveniently when cloning an object.

    Fatal flaw of clone operation

    Can clone really achieve the ideal copying effect? In some cases, you should find that the clone operation is not as perfect as we imagined. Let’s modify the above TV type and then do a test.

    Each TV will come with a remote control, so we will have a remote control class. The remote control and the TV are an "aggregation" relationship (relative to the "combination" relationship, which is a weaker dependency relationship, because Generally speaking, the TV can be used normally even without a remote control). Now our TV objects should all hold a reference to the remote control object. Take a look at the code below

    PHP code

    1. /**
    2. * TV type
    3. ​*/  
    4. class Television   
    5. {  
    6.       
    7.     /**
    8. * TV number
    9. ​​*/  
    10.     protected $_identity    = 0;  
    11.       
    12.     /**
    13. *Screen height
    14. ​​*/  
    15.     protected $_screenLength = 300;  
    16.       
    17.     /**
    18. *Screen width
    19. ​​*/  
    20.     protected $_screenHight  = 200;  
    21.       
    22.     /**
    23. * TV appearance color
    24. ​​*/  
    25.     protected $_color        = 'black';  
    26.       
    27.     /**
    28. * Remote control object
    29. ​​*/  
    30.     protected $_control      = null;  
    31.       
    32.     /**
    33. * Load the remote control object in the constructor
    34. ​​*/  
    35.     public function __construct()  
    36.     {  
    37.         $this->setControl(new Telecontrol());  
    38.     }  
    39.   
    40.     /**
    41. * *Set remote control object
    42. ​​*/  
    43.     public function setControl(Telecontrol $control)  
    44.     {  
    45.         $this->_control = $control;  
    46.         return $this;  
    47.     }  
    48.       
    49.     /**
    50. * Return the remote control object
    51. ​​*/  
    52.     public function getControl()  
    53.     {  
    54.         return $this->_control;  
    55.     }      
    56.       
    57.     /**
    58. * Return to TV appearance color
    59. ​​*/  
    60.     public function getColor()  
    61.     {  
    62.         return $this->_color;  
    63.     }  
    64.       
    65.     /**
    66. *Set the appearance color of the TV
    67. ​​*/  
    68.     public function setColor($color)  
    69.     {  
    70.         $this->_color = (string)$color;  
    71.         return $this;  
    72.     }  
    73.   
    74.    /**
    75. * Return to TV number
    76. ​​*/  
    77.     public function getIdentity()  
    78.     {  
    79.         return $this->_identity;      
    80.     }  
    81.       
    82.     /**
    83. *Set TV number
    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. * Remote Control Category
    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. //Reset a remote control object
    5. $this->setControl(new Telecontrol());
    6. }

    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 there are multiple references to other objects in the copied object, we must reset them one by one in the __clone method. What is even worse is if the class of the copied object is provided by a third party. Provided, 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.

    Solution 2: Use serialization for deep copy

    PHP has serialize (serialize) and deserialize (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 is copied. In the JAVA language, this process is called "refrigeration" and "thawing". Below we will test this method:

    PHP code

    1. $tv1 = new Television();
    2. $tv2 = unserialize(serialize($tv1));//Serialize and then deserialize
    3. $contr1 = $tv1->getControl(); //Get the remote control contr1 of tv1
    4. $contr2 = $tv2->getControl(); //Get the remote control of tv2 contr2
    5. echo $tv1; //The object id of tv1 is #1
    6. echo '
      ';
    7. echo $contr1; //The object id of contr1 is #2
    8. echo '
      ';
    9. echo $tv2; //The object id of tv2 is #4
    10. echo '
      ';
    11. 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

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478553.htmlTechArticleThis article will discuss the object copying technology of PHP5 from simple to in-depth. Original article, please respect the copyright. There may be errors or inappropriate The office also hopes to point out the origin of object replication and why objects have duplicates...
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