PHP中 __toString()办法详解
发布时间:09/01 来源:未知 浏览:
关键词:
作用:
__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()办法详解的具体内容,更多请关注百分百源码网其它相关文章!