PHP Cloning clone
In the actual programming process, we often encounter this situation: there is an object A, in a moment a is already included in a number of valid values, it may be necessary to a exactly the same new object B, and then any changes to B will not affect the value of a, that is, A and B is two separate objects, But the initial value of B is determined by the A object.
In the PHP language, this requirement cannot be satisfied with simple assignment statements. There are many ways to meet this requirement, but the implementation of the Clone () method is the simplest and most efficient means.
Core:
$obj = new Mycloneable ();
$obj 2 = Clone $obj;
The references in all the attributes remain unchanged, pointing to the original variable.
classbyref{var $prop; function__construct () {$this->prop =&$this-prop; //& Address reference points to the same memory address $this->PROP1 = ' Haha, I am here '; } function__clone () {$this->prop=2;//$a->prop is now 2 }}$a=NewByRef;$a->prop = 1;Echo' Original object: ';Var_dump($a);Echo' <br><br> ';$b=Clone $a;//this sentence is replaced by $b = $a, the result is still 3, but does not trigger Byref::__clone, prop will not become 2. In this case, the $b->prop reference is not changed after cloning .Echo' Original object: ';Var_dump($a);Echo' <br> ';Echo' Clone object: ';Var_dump($b);Echo' <br><br> ';$b->prop = 3;//$a->prop is now 3$b->PROP1 = ' oh,u move ';//B's Prop1 has changed, and A's prop1 hasn't changed.Echo' Original object: ';Var_dump($a);Echo' <br> ';Echo' Clone object: ';Var_dump($b);Echo' <br><br> ';Echo' Reference to the original object prop: ';Echo $a->prop;Echo' <br> ';Echo' Clone object's Reference prop: ';Echo $b->prop;
################## #结果 ###################
The original object: Object (BYREF) #6 (2) {["Prop"]=> &int (1) ["Prop1"]=> string ("Haha, I am here"}
Original object: Object (BYREF) #6 (2) {["Prop"]=>&int (2) ["Prop1"]=> string ("Haha, I am here"}
Clone object: Object (BYREF) #7 (2) {["Prop"]=>&int (2) ["Prop1"]=> string "haha, I am here"}
Original object: Object (BYREF) #6 (2) {["Prop"]=>&int (3) ["Prop1"]=> string ("Haha, I am here"}
Clone object: Object (BYREF) #7 (2) {["Prop"]=>&int (3) ["Prop1"]=> string (9) "Oh,umove"}
Reference to the original object Prop:3
References to clone objects Prop:3
Turn http://blog.sina.com.cn/s/blog_54e38bdc0100xhm7.html
PHP Clone __clone