您的位置 首页 php

PHP中 __toString()方法详解

__toString(),类被当成字符串时的回应方法

作用:

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

注意:

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

警告:

不能在 __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;    }    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()方法详解的详细内容,更多请关注求知技术网其它相关文章!

文章来源:智云一二三科技

文章标题:PHP中 __toString()方法详解

文章地址:https://www.zhihuclub.com/3838.shtml

关于作者: 智云科技

热门文章

网站地图