__toString(), the response method when the class is treated as a string
Function:
__toString() method is used for a class How to respond when it is treated as a string. For example what `echo $obj;` should display.
Note:
This method must return a string, otherwise a fatal error of level `E_RECOVERABLE_ERROR` will be issued.
Warning:
Cannot throw exceptions in the __toString() method. Doing so will result in a fatal error.
Code:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } public function __toString() { return 'go go go'; } } $person = new Person('小明'); // 初始赋值 echo $person;
Result:
go go go
So what happens if there is no __toString() magic method in the class? Let’s test it:
Code:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } } $person = new Person('小明'); // 初始赋值 echo $person;
Result:
Catchable fatal error: Object of class Person could not be converted to string in D:\phpStudy\WWW\test\index.php on line 18 很明显,页面报了一个致命错误,这是语法所不允许的。
The above is the detailed content of Detailed explanation of __toString() method in PHP. For more information, please follow other related articles on the PHP Chinese website!