PHP魔术方法之 __toString()

__toString()是快速获取对象的字符串信息的便捷方式,似乎魔术方法都有一个“自动“的特性,如自动获取,自动打印等,__toString()也不例外,它是在直接输出对象引用时自动调用的方法。

 

__toString()的作用

 

当我们调试程序时,需要知道是否得出正确的数据。比如打印一个对象时,看看这个对象都有哪些属性,其值是什么,如果类定义了toString方法,就能在测试时,echo打印对象体,对象就会自动调用它所属类定义的toString方法,格式化输出这个对象所包含的数据。


class Person{
    private $name = "";

    function __construct($name = ""){
        $this->name = $name;
    }
    function say(){
        echo "Hello,".$this->name."!
"; } function __tostring(){//在类中定义一个__toString方法 return "Hello,".$this->name."!
"; } } $WBlog = new Person('WBlog'); echo $WBlog;//直接输出对象引用则自动调用了对象中的__toString()方法 $WBlog->say();//试比较一下和上面的自动调用有什么不同

程序输出:

Hello,WBlog!

Hello,WBlog! 

如果不定义“__tostring()”方法会怎么样呢?例如在上面代码的基础上,把“ __tostring()”方法屏蔽掉,再看一下程序输出结果:

 Catchable fatal error: Object of class Person could not be converted to string

 由此可知如果在类中没有定义“__tostring()”方法,则直接输出以象的引用时就会产生误法错误,另外__tostring()方法体中需要有一个返回值。

原博地址:https://www.cnblogs.com/perseverancevictory/p/4216052.html

你可能感兴趣的:(PHP魔术方法之 __toString())