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
PHP code
echo 'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
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