关于奇矩互动奇矩互动招贤纳士奇矩互动优质虚拟主机Discuz!商业用户享有本站VIP服务LAMP环境配置手册(CentOS5.1)
发新话题
打印

php5.2以前 tostring方法使用的bug

php5.2以前 tostring方法使用的bug

原文 http://www.jcinacio.com/2007/04/ ... o-magic-before-520/
I was confident that using one of php5’s magic methods, __toString() would just work, but the fact is that the following code works in php version 5.2.1 but not in 5.1.6:

You can try this for yourself:
<?php
class ToStringTest {
        protected $content;

        public function __construct($content) {
                $this->content = $content;
        }

        public function add($content) {
                $this->content .= ‘ ‘ . $content;
        }

        public function __toString() {
                return $this->content;
        }
}

$A = new ToStringTest(‘Hello World (A)’);
$B = new ToStringTest(‘Hello World (B)’);

$A->add(‘!’);
$B->add( $A );

echo $A;
echo “\n“;

echo $B;
echo “\n“;
?>

Outputs:
Hello World !
Hello World Hello World !

In php 5.2.1

and
Hello World !
Hello World Object id #1

In php 5.1.6

And then it hit me:

    It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().

Small piece of advise: always be sure to know what is a certain function’s behavior in the possible php versions your code will be running, or risk bad surprises.
Meanwhile… use
$SomeObject->_toString();
真正的尊敬,既不属于那些批评别人头头是道的人,也不是属于给强人指出过错、指点别人哪里做的不好的人。真正的尊敬,是属于那些勇于亲身投入战场,脸上沾满了尘土、汗水和鲜血的奋斗者们。他们坚持不懈的努力,尽管曾经犯下错误,并一再失败,但他们满怀激情,执著不懈,将生命奉献于崇高的事业。他们为经过艰辛努力最终取得的伟大成就而自豪,如果失败,他们也败得荣耀。因此,那些既没赢得过胜利,也没懂得什么叫做失败的,冷漠、胆怯的灵魂,是永远也无法与这些真正值得尊敬的人相提并论的。
http://www.cnedwin.com

TOP

发新话题