search
HomeBackend DevelopmentPHP TutorialIn-depth discussion of PHP5 object copy technology_PHP tutorial

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
php5和php8有什么区别php5和php8有什么区别Sep 25, 2023 pm 01:34 PM

php5和php8的区别在性能、语言结构、类型系统、错误处理、异步编程、标准库函数和安全性等方面。详细介绍:1、性能提升,PHP8相对于PHP5来说在性能方面有了巨大的提升,PHP8引入了JIT编译器,可以对一些高频执行的代码进行编译和优化,从而提高运行速度;2、语言结构改进,PHP8引入了一些新的语言结构和功能,PHP8支持命名参数,允许开发者通过参数名而不是参数顺序等等。

源码探秘:Python 中对象是如何被调用的?源码探秘:Python 中对象是如何被调用的?May 11, 2023 am 11:46 AM

楔子我们知道对象被创建,主要有两种方式,一种是通过Python/CAPI,另一种是通过调用类型对象。对于内置类型的实例对象而言,这两种方式都是支持的,比如列表,我们即可以通过[]创建,也可以通过list(),前者是Python/CAPI,后者是调用类型对象。但对于自定义类的实例对象而言,我们只能通过调用类型对象的方式来创建。而一个对象如果可以被调用,那么这个对象就是callable,否则就不是callable。而决定一个对象是不是callable,就取决于其对应的类型对象中是否定义了某个方法。如

详解Javascript对象的5种循环遍历方法详解Javascript对象的5种循环遍历方法Aug 04, 2022 pm 05:28 PM

Javascript对象如何循环遍历?下面本篇文章给大家详细介绍5种JS对象遍历方法,并浅显对比一下这5种方法,希望对大家有所帮助!

php5如何改80端口php5如何改80端口Jul 24, 2023 pm 04:57 PM

php5改80端口的方法:1、编辑Apache服务器的配置文件中的端口号;2、辑PHP的配置文件以确保PHP在新端口上工作;3、重启Apache服务器,PHP应用程序将开始在新的端口上运行。

深入了解HTTP状态码100:它代表什么意思?深入了解HTTP状态码100:它代表什么意思?Feb 20, 2024 pm 04:15 PM

深入了解HTTP状态码100:它代表什么意思?HTTP协议是现代互联网应用中最为常用的协议之一,它定义了浏览器和Web服务器之间进行通信所需的标准规范。在HTTP请求和响应的过程中,服务器会向浏览器返回各种类型的状态码,以反映请求的处理情况。其中,HTTP状态码100是一种特殊的状态码,用来表示"继续"。HTTP状态码由三位数字组成,每个状态码都有特定的含义

Vue中如何使用v-for指令循环输出对象Vue中如何使用v-for指令循环输出对象Jun 11, 2023 am 08:51 AM

在Vue中,v-for是一种指令,在模板中使用它可以对数组或对象进行循环操作。v-for指令用于循环渲染数据,它是Vue中非常有用的指令之一。在Vue中,使用v-for指令循环输出对象的方式和循环输出数组的方式类似,只需要稍作区别即可。如何使用v-for指令循环输出对象呢?下面我们将分以下几个部分进行讲解。一、v-for指令的基本使用v-for指令的基本语法

php5没有监听9000端口如何解决php5没有监听9000端口如何解决Jul 10, 2023 pm 04:01 PM

php5没有监听9000端口解决方法步骤:1、检查PHP-FPM配置文件;2、重启PHP-FPM服务;3、关闭防火墙或配置端口转发;4、检查其他进程是否占用9000端口。

深入了解Linux ldconfig深入了解Linux ldconfigMar 14, 2024 pm 03:39 PM

Linuxldconfig是一个用于动态链接库管理的工具,可以帮助系统在运行时找到并加载共享库。它主要用于更新系统的动态链接器运行时连接库缓存,以保证程序可以正确链接到共享库。ldconfig主要用于两个方面:一是添加、删除共享库路径,并更新相关信息到配置文件中;二是根据配置文件中的路径重新生成动态连接库链接器的缓存。接下来将介绍如何使用ldconf

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool