热搜:NVER node 开发 php

php面向对象之toString()

2024-07-23 11:05:01
php面向对象之toString()

__toString()的作用


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

下面我们来看一个__toString()的实例

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

程序输出:

Hello,Bindao!

Hello,Bindao!


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


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


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