php 5.1.6 magic __toString方法

nac*_*10f 5 php tostring magic-methods

在codeigniter我试图使用这个插件,这需要我在我的模型中实现一个toString方法.我的toString方法就是这么做的

public function __toString()
{
    return (string)$this->name;
}
Run Code Online (Sandbox Code Playgroud)

在我的本地机器上使用php 5.3一切正常,但是在生产服务器上使用php 5.1.6它显示"对象ID#48",其中该对象的name属性的值应该出现.....我发现了一些关于这里问题但我还是不明白......我怎么能解决这个问题?

Ste*_*rig 7

class YourClass 
{
    public function __toString()
    {
        return $this->name;
    }
}
Run Code Online (Sandbox Code Playgroud)

PHP <5.2.0

$yourObject = new YourClass();
echo $yourObject; // this works
printf("%s", $yourObject); // this does not call __toString()
echo 'Hello ' . $yourObject; // this does not call __toString()
echo 'Hello ' . $yourObject->__toString(); // this works
echo (string)$yourObject; // this does not call __toString()
Run Code Online (Sandbox Code Playgroud)

PHP> = 5.2.0

$yourObject = new YourClass();
echo $yourObject; // this works
printf("%s", $yourObject); // this works
echo 'Hello ' . $yourObject; // this works
echo 'Hello ' . $yourObject->__toString(); // this works
echo (string)$yourObject; // this works
Run Code Online (Sandbox Code Playgroud)


Joe*_*ynn 2

升级PHP

我正在处理同样的问题,我怀疑你最好的选择是将生产服务器上的 php 升级到>= 5.2.0

将来(我目前正在艰难地学习这一点),请尝试在您将部署到的同一版本上进行开发。