In the preceding PHP object-oriented object and reference , "$b = $a" way to copy an object is to pass the object's address, instead of passing the object's value (content), we can clone the object to achieve the object's content and reference replication
The invocation of the object by means of a reference, the real call is the same object, sometimes need to build a copy of the object, change the original object does not want to affect the copy, in PHP can be based on the current object to clone an identical object, the cloned copy and the original two objects completely independent without interfering with each other
Cloning an object using the "clone" keyword in PHP
<?phpclass person {public $name; function __construct ($name = "") { $this->name = $name; } function say () { echo "I'm called:". $this->name. " <br> "; }} $Person =new person ("Zhang San"); $Person 1=clone $Person; Clone (copy) an object using the Clone keyword, create a copy of an object//$Person 1= $Person ///This is not a copy object, but rather a reference to the object that accesses the object $Person->say (); My name is: Zhang San $Person 1->say (); My name is: Zhang San
The cloned copy has the same classes and attributes as the original
if ($Person = = $Person 1) { = = compares the content value echo "person and Person1 have the same class and attribute";} else{ return false;}
Program output: Person and Person1 have the same classes and attributes
Cloned copies are stored in a different location from the original
if ($Person = = = $Person 1) { echo "person and Person1 have the same class and attribute and are stored in the same location";} else{ return false;}
The program result is false.
Cloned copy and original independent without interfering with each other
Let's change the original attribute value and see what the effect is.
$Person =new person ("Zhang San"); $Person 1=clone $Person; $Person 1-> name= ' John Doe '; $Person->say (); My name is: Zhang San $Person 1->say (); My name is: John Doe
It is shown that the cloned copy and the original two objects are completely independent without interfering with each other.
__clone () method
If you need to re-assign a value to a member property when cloning a cloned copy object, you can declare a magic method "__clone" in the class
<?phpclass person {public $name; function __construct ($name = "") { $this->name = $name; } function __clone () {//is called automatically when an object is cloned to re-assign a value to a new object $this->name = ' John Doe '; } function say () { echo "I'm called:". $this->name. " <br> "; }} $Person =new person ("Zhang San"); $Person 1=clone $Person; $Person->say (); $Person 1->say (); ? >
Summary: The __clone () method can be used as the constructor of the new object to make some initial modifications to the new object
Object clones clone and __clone () functions