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 classclasstestclass{ Public $foo; Public function__construct ($foo) { $this->foo =$foo; } //define a __tostring method and return a member property $foo Public function__tostring () {return $this-foo; }}$class=NewTestClass (' Hello ');//Direct Output ObjectEcho $class;?>
PHP Object-oriented (OOP): __tostring () method