PHP魔术方法__toString()

2018-09-17 19:00 By "Powerless" 3292 0 2

注意:该方法必须返回字符串,否则会抛出"E_RECOVERABLE_ERROR"级别的异常。在__toString()方法中也不能抛出异常。

示例代码如下:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __toString()
    {
        return  'go go go';
    }
}
$person = new Person('John'); // 赋初始值
echo $person;

输出结果如下:

go go go

如果类中没有定义__toString()会怎样?我们来试试看。

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
}
$person = new Person('John'); // 赋初始值
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

可见,它会在页面上报告致命错误,说明这种用法不允许。

评 论

View in WeChat

Others Discussion

  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • PHP设计模式 - 委托模式
    Posted on 2019-04-25 16:15