PHP中 __toString()方法详解-php教程

资源魔 19 0
__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()办法详解的具体内容,更多请存眷资源魔其它相干文章!

标签: php开发教程 php开发资料 php开发自学 toString()

抱歉,评论功能暂时关闭!