We all know that after we instantiate a class, when accessing the properties of the class, we always access them in the format of $instantiation name->property name. So have you ever directly output the object using echo or print? Try the results. Some people say that this should not work, and an error will be reported. Yes, such direct output will indeed report an error, but when we use the magic method __toString, it will be fine. The __toString() method will first convert the object into a string before outputting it, so that it can be output using echo or print.
Instance analysis:
<?php header("content-type:text/html;charset=utf-8"); class Preson{ public $name; private $age; function __construct($name,$age) { $this->name = $name; $this->age = $age; } public function __toString() { return $this->name . '今年已经' . $this->age . '岁了'; } } $preson = new Preson('小明',18); echo $preson;
Code analysis:
We first create a human class, define attributes, create a constructor, then we instantiate this class, and finally directly echo the class name. You will find that the error message will be displayed on the page: Object of class Preson could not be converted to string in D:\WWW\tostring.php on line 15. It means that the object's class cannot be converted to a string and cannot be output. So we just add the __toString() method, and just return the required results directly in the method.
The above is the detailed content of Detailed explanation of magic method ___toString() instance (php advanced object-oriented tutorial). For more information, please follow other related articles on the PHP Chinese website!