In PHP can be based on the existing objects to clone the first exact same object, after cloning, the original and the copy two objects completely independent, non-interference.
<?php
Class person{
Private $name;
Private $sex;
Private $age;
function __construct ($name = "", $sex = "", $age = "") {
$this->name= $name;
$this->sex= $sex;
$this->age= $age;
}
function say () {
echo "My Name:" $this->name. " ; Gender: ". $this->sex." ; Age: ". $this->age." <br/> ";
}
}
$person 1=new person ("Zhang San", "male", "40");
$person 2=clone $person 1;
$person 1->say ();
$person 2->say ();
?>
The result of the code operation is:
650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/89/BD/wKiom1gbAmOQ6LqyAAAjzt41EVk457.png-wh_500x0-wm_3 -wmp_4-s_2661580741.png "title=" capture. PNG "alt=" Wkiom1gbamoq6lqyaaajzt41evk457.png-wh_50 "/>
If you need to assign an initial value to a member property when cloning a cloned copy object, you can declare a magic method __clone () in the class. This method is called automatically when the object is cloned, so the cloned copy can be reinitialized by this method. The __clone () method does not require any arguments, and the method automatically contains references to two objects of $this and $that, $this a reference to the replica object, and $that is a reference to the original object.
<?php
Class person{
Private $name;
Private $sex;
Private $age;
function __construct ($name = "", $sex = "", $age = "") {
$this->name= $name;
$this->sex= $sex;
$this->age= $age;
}
function __clone () {
$this->name= "Zhang San";
$this->sex= "female";
$this->age= "20";
}
function say () {
echo "My Name:" $this->name. " ; Gender: ". $this->sex." ; Age: ". $this->age." <br/> ";
}
}
$person 1=new person ("Zhang San", "male", "40");
$person 2=clone $person 1;
$person 1->say ();
$person 2->say ();
?>
The result of the code operation is:
650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M01/89/BD/wKiom1gbCILg68cKAAApcoNhxLw981.png-wh_500x0-wm_3 -wmp_4-s_1630092742.png "title=" capture. PNG "alt=" Wkiom1gbcilg68ckaaapconhxlw981.png-wh_50 "/>
This article is from the "12145704" blog, please be sure to keep this source http://12155704.blog.51cto.com/12145704/1869035
Clone Object Clone