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 PHP5 we use the "clone" keyword to clone the object;
<?php class person{//The following is a member of the person attribute var $name;//person's name Var $sex;//Human gender var $age;//person's age//define a constructor method parameter for attribute name $name, gender $sex and age $ag E assignment 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); Clone a new object using "Clone" P2, with the same properties and methods as the P1 object. $p 2=clone $p 1; $p 2->say ();?>
PHP5 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, if you want to change after cloning
The contents of the original object, you need to override the original property and method in Clone (), 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;
<?php//defines the class staff, which includes the attribute ID and name class staff {private $id; Private $name; function SetID ($id) {$this->id = $id; } function GetID () {return $this->id; } function SetName ($name) {$this->name = $name; } function GetName () {return $this->name; }//This is clone function clone () {$this->id = $this->id + 1; }}//Create a new staff object and initialize $ee 1 = new staff (); $ee 1->setid ("145"); $ee 1->setname ("Simon"); Clones a new object $ee 2 = Clone $ee 1; Reset the ID value of the new object//$ee 2->setid ("146"); Output ee1 and Ee2 echo "Ee1 ID:". $ee 1->getid (). " <br> "; echo "Ee1 Name:". $ee 1->getname (). " <br> "; echo "Ee2 ID:". $ee 2->getid (). " <br> "; echo "Ee2 Name:". $ee 2->getname (). " <br> ";?