In-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
- /**
- * TV type
- */
- 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()
- {
- using out return $this->_color; }
- /**
- *Set the appearance color of the TV
- */
- Public function setColor($color)
- {
- $this->_color = (string)$color;
- return $this; }
- }
- $tv1 = new Television();
- $tv2 = $tv1;
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
- $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 '
'; - //Change 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
- /**
- * TV type
- */
- 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 the appearance color of the TV
- */
- public function setColor($color)
- {
- $this->_color = (string)$color;
- return $this;
- }
- /**
- * Return to 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);
- }
- }
- $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
- /**
- * TV type
- */
- 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;
- }
- /**
- * Return the remote control object
- */
- public function getControl()
- {
- return $this->_control;
- }
- /**
- * Return to TV appearance color
- */
- public function getColor()
- {
- return $this->_color;
- }
- /**
- *Set the appearance color of the TV
- */
- public function setColor($color)
- {
- $this->_color = (string)$color;
- return $this;
- }
- /**
- * Return to 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
- {
- }
- $tv1 = new Television();
- $tv2 = clone $tv1;
- $contr1 = $tv1->getControl(); //获取tv1的遥控器contr1
- $contr2 = $tv2->getControl(); //获取tv2的遥控器contr2
- echo $tv1; //tv1的object id 为 #1
-
echo '
'; - echo $contr1; //contr1的object id 为#2
-
echo '
'; - echo $tv2; //tv2的object id 为 #3
-
echo '
'; - echo $contr2; //contr2的object id 为#2
- public function __clone()
- {
- $this->setIdentity(0);
- //Reset a remote control object
- $this->setControl(new Telecontrol());
- }
- $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 of tv2 contr2
- 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
';
';
';
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
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
下面我们来复制这样的一个电视机对象。
PHP代码
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
下面复制这样的一个电视机对象并且观察电视机的遥控器对象。
PHP代码
经过复制之后,我们查看对象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代码
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
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

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools