As we said before, the method that declares the method name of "__" in the class (provided to us by PHP) is the method that executes automatically at a certain time under different circumstances, and the "__tostring ()" method is also automatically called, which is called automatically when the object reference is directly exported. We said before that the object reference is a pointer, for example: "$p =new person ()", $p is a reference, we can not use the Echo Direct output $p, this will output "catchable fatal error:object of class person C Ould not is converted to string "error, if you define a class inside the" __tostring () "method, in the direct output object reference, will not produce an error, but automatically called the" __tostring () "method, output" __ The character returned in the ToString () "method, so the" __tostring () "method must have a return value (return statement).
<?php//Declare A simple classclass testclass{public $foo;p ublic function __construct ($foo) {$this->foo = $foo;} Define a __tostring method, and add a member property $foopublic function __tostring () {return $this->foo;}} $class = new TestClass (' Hello ');//Direct Output object echo $class;? >
Above example output: Hello
"Getting Started with the PHP object-oriented (OOP) Programming Tutorial" 16.__tostring () method