php __tostring 与 tostring

原文:
 
问:内容是一样,不知道前面那两个特殊的下划线有什么意义,是同一个类中的两个方法?
function __toString()
{
        return $this->content;
 }

//输出字符串
 function toString()
{
        return $this->content;
}
 
回答:
  执行的结果相同. 区别在于,
  前一个是魔术函数, 在需要字符串值的地方会自动调用它进行对象的类型转换.
  后一个需要在代码中明确调用才有机会执行.
 
实例
class MyClass
{
    public function __toString()
    {
        return 'call __toString()';
    }
    public function toString()
    {
        return 'call toString()';
    }
}

$my = new MyClass();
echo $my . '<br />'; //自动调用(隐式)__toString转成string
echo $my->toString() . '<br />'; //调用(显式)toString去转成string
echo $my->__toString() . '<br />'; //如果这样调用, 代码会不好看
echo (string)$my . '<br />';
  __toString()会在需要转成字符串时, 会隐式自动调用它, 在PHP内部.  这个也是来自JAVA的. 建议在__toString()中调用toString(), 这样就不会代码重复了.
 

转自:

  单党育的BLOG.PHP -toString()辨析.http://blog.sina.com.cn/s/blog_569767bf01000c37.html

知识共享许可协议
作品Tim Zhang创作,采用知识共享署名 3.0 中国大陆许可协议进行许可。 。
原文地址:https://www.cnblogs.com/ccdc/p/2099322.html