PHP魔术方法之__toString()方法,魔术__tostring
分享于 点击 32922 次 点评:18
PHP魔术方法之__toString()方法,魔术__tostring
__tostring()方法:在直接输出对象引用的时候,就不会产生错误,而是自动调用了__tostring()方法,输出__tostring()方法中返回的字符串
通俗来说就是 对象一般是使用print_r() 或 var_dump() 来打印访问
但对于一般闲的人来说直接 使用 echo 输出对象时,必定会报错的,原因是对象无法使用echo的。
这个时候如果想解决这个错误,咱们应该怎么操作呢?
可以很好的利用__tostring()这个魔术方法
但是切记使用__toString() 时返回值一定要使用return 来进行返回。
<?php
header("content-type:text/html;charset=utf-8");
class demo{
public $foo;
public function __construct($foo){
$this->foo=$foo;
}
//定义一个__toString()方法时,返加一个成员属性$foo
public function __toString(){
return $this->foo;
}
}
$demo=new demo('hello PHP成员');
echo $demo;
相关文章
- 暂无相关文章
用户点评