We already know that when calling an object using a pass-by-reference method, the actual call is the same object. Sometimes it is necessary to create a copy of the object. When changing the original object, we do not want to affect the copy. In PHP, you can use Use the current object to clone an identical object. The cloned copy is completely independent of the original two objects and does not interfere with each other.
Let’s take a simple example to look at the usage of cloning:
name = $name; $this->location = $location; } function play(){ //创建方法 echo '我要玩' . $this->name.$this->location; } } $character1 = new Character('亚索','中单'); //实例化一个类 $character2 = clone $character1; //将实例化的类再克隆出来一个 $character1->play(); //调用方法执行 echo '
'; $character2->play();
The results of the above examples are all ‘I want to play Yasuo mid laner’.
We mentioned above that the cloned copy is independent of the original and does not interfere with each other. What does this mean?
It’s still the same example as above, just slightly changed.
name = $name; $this->location = $location; } function play(){ //创建方法 echo '我要玩' . $this->name.$this->location; } } $character1 = new Character('亚索','中单'); //实例化一个类 $character2 = clone $character1; $character2->location = '上单'; $character1->play(); //调用方法执行 echo '
'; $character2->play();
The results of the above example are 'I want to play Yasuo in the mid lane' and 'I want to play Yasuo in the top lane'.
It can be seen from the example that the cloned copy and the original two objects are completely independent and do not interfere with each other.
__Usage of clone
Many times we not only want to clone an object, but also want the object to have its own properties and methods. Then we need to create a __clone method in the class. This method is similar to the constructor and destructor in that it is not called directly.
Still taking the above example as an example:
name = $name; $this->location = $location; } function __clone(){ $this -> location = '上单'; } function play(){ //创建方法 echo '我要玩' . $this->name.$this->location; } } $character1 = new Character('亚索','中单'); //实例化一个类 $character2 = clone $character1; $character1->play(); //调用方法执行 echo '
'; $character2->play();
A good feature of the __clone method is that it can be called after using the default behavior to create a copy. In this way, at this stage, you can just Change what you want to change.
The most common functionality added in the __clone method is to ensure that class attributes treated as references are copied correctly. If you want to clone a class that contains a reference to an object, you may need to get a second copy of the object, not a second reference to the object, so that's why you add that code in the __clone method.
The above is the detailed content of PHP object-oriented object cloning method. For more information, please follow other related articles on the PHP Chinese website!