: This article mainly introduces the PHP magic method __clone _ toString. if you are interested in the PHP Tutorial, refer to it. In versions later than php5, classes can use magic methods. Php requires that all methods starting with two underscores (_) are retained as magic methods. Therefore, we recommend that you do not use the _ open header for function names unless you want to reload the existing magic methods.
Currently, php's existing magic methods include _ construct ,__ destruct ,__ call ,__ get ,__ set ,__ isset ,__ unset ,__ sleep ,__ wakeup ,__ toString, __set_state and _ clone.
Let's take a look at two magic methods: __clone () and _ toString ().
_ 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:
1 million I Love 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
The above describes the PHP magic method: _ clone _ toString, including the PHP magic method content, hope to be helpful to friends who are interested in the PHP Tutorial.