As we all know, after we instantiate a class, accessing the properties of a class is accessed in such a format as the name of the property named-----so do you ever try to test the result directly with Echo or print output. Some people say, this should be not possible, will error it. Yes, this direct output does make an error, but when we use the Magic method to __tostring it. The __tostring () method first passes the object to a string in the output so that it can be output with echo or print.
Example Analysis:
<?phpheader ("Content-type:text/html;charset=utf-8"); class Preson{public $name;p rivate $age; function __construct ($name, $age) {$this->name = $name; $this->age = $age;} Public Function __tostring () {return $this->name. ' This year has been '. $this->age. ' old ';}} $preson = new Preson (' xiaoming '); Echo $preson;
Code Analysis:
We first create a human class, define properties, create a constructor method, and then instantiate the class, and finally echo the class name directly. It will be found that the error message will be displayed on the page: Object of Class Preson could not being converted to string with D:\WWW\tostring.php on line 15. This means that the object's class person cannot be converted to a string that cannot be exported. So we add the __tostring () method, so we can return the desired result directly in the method.