__toString(),类被当成字符串时的回应方法 作用: __toString() 方法用于一个类被当成字符串时应怎样回应。例如 `echo $obj;` 应该显示些什么。 注意: 此方法必须返回一个字符串,否则将发出一条 `E_RECOVERABLE_ERROR` 级别的致命错误。 警告: 不能在 __toString() 方法中抛出异常。这么做会导致致命错误。 代码: <?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; 结果: go go go 那么如果类中没有 __toString() 这个魔术方法运行会发生什么呢?让我们来测试下: 代码: <?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; 结果: Catchable fatal error: Object of class Person could not be converted to string in D:\phpStudy\WWW\test\index.php on line 18
很明显,页面报了一个致命错误,这是语法所不允许的。 以上就是PHP中 __toString()方法详解的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |