A special method name "__clone ()" method is defined in PHP5. is a method that is invoked automatically when an object is cloned, using the "__clone ()" method to create an object with the same properties and methods as the original object, and if you want to change the contents of the original object after cloning, you need to In Clone () rewrite the original properties and methods, the "__clone ()" method can have no parameters, it automatically contains $this and $that two pointers, $this point to the copy, and the $that point to the original, specific examples are as follows:
The code is as follows:
Class Person {
The following are the member properties of the person
var $name; Person's name
var $sex; The gender of the person
var $age; The age of the person
Define a constructor parameter to assign the attribute name $name, gender $sex, and age $age
function __construct ($name = "", $sex = "", $age = "")
function __construct ($name, $sex, $age) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
This person can speak the way to speak his own attributes
function say () {
echo "My name is:". $this->name. "Sex:". $this->sex. "My Age is:". $this
->age. "
";
}
The method that is invoked automatically when the object is cloned, if you want to change the contents of the original object after cloning, you need to rewrite the original properties and Methods in __clone ().
function __clone () {
The copy of the $this refers to the P2, and the $that is pointing to the original P1, so that in this method, the properties of the copy are changed.
$this->name = "I am a copy of the John $that->name";
$this->age = 30;
}
}
$p 1 = new Person ("John", "Male", 20);
$p 2 = clone $p 1;
$p 1->say ();
$p 2->say ();
?>
The results of successfully running this PHP program are as follows:
The code is as follows:
My name is: John Sex: Male My age is: 20
My name is: I am a copy of John Sex: Male My age is: 20