PHP中的__toString() 是什么东西

__toString()  是魔术方法的一种,具体用途是当一个对象被看成字符串对待的时候,会触发这个魔术方法 如下说明摘自PHP官方手册php

public string __toString ( void )

__toString() 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。此方法必须返回一个字符串,不然将发出一条 E_RECOVERABLE_ERROR 级别的致命错误。oop

Warning

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

Example #2 简单示例spa

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) 
    {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

 

以上例程会输出:.net

Hello

须要指出的是在 PHP 5.2.0 以前,__toString() 方法只有在直接使用于 echo 或 print 时才能生效。PHP 5.2.0 以后,则能够在任何字符串环境生效(例如经过 printf(),使用 %s 修饰符),但不能用于非字符串环境(如使用 %d 修饰符)。自 PHP 5.2.0 起,若是将一个未定义 __toString() 方法的对象转换为字符串,会产生 E_RECOVERABLE_ERROR 级别的错误。code

相关文章
相关标签/搜索