Sometimes we need to use two or more of the same objects in a project, if you re-create the object using the "new" keyword, then assign the same attributes, it is cumbersome and error-prone, so it is necessary to completely clone an object exactly as it is, And after cloning, two objects do not interfere with each other.
In PHP4 we use the "clone" keyword to clone the object;
<?class person{//Below is a member of the human attribute var $name;//person's name Var $sex;//Human gender var $age;//person's age//define a constructor method parameter for property name $name, gender $sex and age $ Age assigns function __construct ($name = "", $sex = "", $age = "") {$this->name = $name; $this->sex = $sex; $this->age = $age;} This person can speak in a way that speaks his own attribute function say () {echo "My name is called:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. "<br>";}} $p 1 = new Person ("Zhang San", "male", 20);//Use "clone" to clone a new object P2, and P1 objects have the same properties and methods. $p 2=clone $p 1; $p 2->say ();? >
PHP4 defines a special method named "__clone ()" method, which is the method that is called automatically when the object is cloned, and the "__clone ()" method will establish an object that has 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 __clone () Overriding the original properties and methods, the "__clone ()" method can have no parameters, it automatically contains $this and $that two pointers,$this point to the replica , and $that point to the original ;
<?class person{//Below is a member of the human attribute var $name;//person's name Var $sex;//Human gender var $age;//person's age//define a constructor method parameter for property name $name, gender $sex and age $ Age assigns function __construct ($name = "", $sex = "", $age = "") {$this->name = $name; $this->sex = $sex; $this->age = $age;} This person can speak in a way that speaks his own attribute function say () {echo "My name is called:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. "<br>";} Object Cloning method, 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 () {//$this refers to the replica P2, and $that is pointing to the original P1, so in this method, Changed the properties of the replica. $this->name = "I am a fake $that->name"; $this->age = 30;}} $p 1 = new Person ("Zhang San", "male"), $p 2 = clone $p 1; $p 1->say (); $p 2->say (); >
The above example outputs:
My name is called: Zhang San Sex: Male my age is: 20
My name is called: I am false zhang San Sex: Male my age is:
"Getting Started with PHP object-oriented (OOP) programming" 17. Clone Object __clone () method