Home > Backend Development > PHP Tutorial > php __tostring 与 tostring

php __tostring 与 tostring

WBOY
Release: 2016-06-23 14:36:15
Original
1025 people have browsed it

原文:

问:内容是一样,不知道前面那两个特殊的下划线有什么意义,是同一个类中的两个方法?

function __toString(){        return $this->content; }//输出字符串 function toString(){        return $this->content;}
Copy after login

回答:

  执行的结果相同. 区别在于,
  前一个是魔术函数, 在需要字符串值的地方会自动调用它进行对象的类型转换.
  后一个需要在代码中明确调用才有机会执行.

class MyClass{    public function __toString()    {        return 'call __toString()';    }    public function toString()    {        return 'call toString()';    }}$my = new MyClass();echo $my . '<br />'; //自动调用(隐式)__toString转成stringecho $my->toString() . '<br />'; //调用(显式)toString去转成stringecho $my->__toString() . '<br />'; //如果这样调用, 代码会不好看echo (string)$my . '<br />';
Copy after login

 

  __toString()会在需要转成字符串时, 会隐式自动调用它, 在PHP内部.  这个也是来自JAVA的. 建议在__toString()中调用toString(), 这样就不会代码重复了.

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template