首页 > 编程 > PHP > 正文

PHP中 __toString()方法详解

2020-03-22 17:05:32
字体:
来源:转载
供稿:网友
__toString(),类被当成字符串时的回应方法

作用:

__toString() 方法用于一个类被当成字符串时应怎样回应。例如 `echo $obj;` 应该显示些什么。

注意:

此方法必须返回一个字符串,否则将发出一条 `E_RECOVERABLE_ERROR` 级别的致命错误。

警告:

不能在 __toString() 方法中抛出异常。这么做会导致致命错误。

代码:

<?phphtml' target='_blank'>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() 这个魔术方法运行会发生什么呢?让我们来测试下:

代码:

<?phpclass 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()方法详解的详细内容,更多请关注 其它相关文章!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表