PHP magic method _ clone _ toString (5) ,__ clone _ tostring. PHP magic method _ clone _ toString (5) ,__ clone _ tostring _ clone ()-This method is automatically loaded when the object is cloned _ toString () -automatically add the PHP magic method _ clone _ toString (5) ,__ clone _ tostring when the object requires echo to print the output.
_ Clone ()-This method is automatically loaded when the object is cloned.
_ ToString ()-This method is automatically loaded when the object requires echo to print the output.
_ Clone ()
pb = ++self::$pa; } public function __clone(){ $this->pb = 'no zuo no die'; }}$a = new example;$b = new example;$c = clone $b;$b->pb = 'I Love You So Much!';echo $a->pb;echo '
';echo $b->pb;echo '
';echo $c->pb;echo '
';echo $b->pb;?>
The result is as follows:
Thank You So Much! When no zuo no die/* if there is no _ clone () magic method, the result here should be 2 */When I Love You So Much!
The php manual gives us an example that is hard to understand, as shown below:
Instance = + + self: $ instances;} public function _ clone () {$ this-> instance = + self: $ instances ;}} class MyCloneable {public $ object1; public $ object2; function _ clone () {// force copy this-> object, otherwise, it still points to the same object $ this-> object1 = clone $ this-> object1 ;}}$ obj = new MyCloneable (); $ obj-> object1 = new SubObject (); $ obj-> object2 = new SubObject (); $ obj2 = clone $ obj; print ("Original Object: \ n"); print_r ($ obj ); Print ("Cloned Object: \ n"); print_r ($ obj2);?>
Final result
Original Object: MyCloneable Object ([object1] => SubObject Object ([instance] => 1) [object2] => SubObject Object ([instance] => 2) Cloned Object: myCloneable Object ([object1] => SubObject Object ([instance] => 3/* may be hard to understand, in fact, $ obj2 clones the result of the last instance of 2 when cloning, and then executes the SubObject :__ clone method */) [object2] => SubObject Object ([instance] => 2 ))
_ ToString ()
foo = $foo; } public function __toString() { return $this->foo; }}$class = new TestClass('Hello');echo $class;?>
Result
Hello
Http://www.bkjia.com/PHPjc/917481.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/917481.htmlTechArticlePHP magic method _ clone _ toString (5) ,__ clone _ tostring _ clone ()-automatically load this method when the object is cloned _ toString () -When an object requires echo to print the output, it is automatically added...