5

在 codeigniter 中,我尝试使用这个插件,这需要我在我的模型中实现一个 toString 方法。我的 toString 方法只是做

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

在我使用 php 5.3 的本地机器上,一切正常,但在使用 php 5.1.6 的生产服务器上,它显示“Object id#48”,该对象的 name 属性的值应该出现在哪里......我发现了一些关于这里的问题,但我仍然不明白......我该如何解决这个问题?

4

5 回答 5

7
class YourClass 
{
    public function __toString()
    {
        return $this->name;
    }
}

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()

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
于 2010-05-25T07:04:30.630 回答
3

引用手册:

值得注意的是,在 PHP 5.2.0 之前,__toString 方法只有在直接与 echo() 或 print() 结合时才会被调用。自 PHP 5.2.0 起,它在任何字符串上下文中调用(例如在 printf() 中使用 %s 修饰符),但不在其他类型上下文中调用(例如使用 %d 修饰符)。自 PHP 5.2.0 起,将没有 __toString 方法的对象转换为字符串会导致 E_RECOVERABLE_ERROR。

如果您在 PHP < 5.2 中使用 __toString 方法,而不是在回显或打印的上下文中,我认为您已经手动调用了该方法。

于 2010-05-25T06:16:33.537 回答
2

升级 PHP

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

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

于 2011-09-01T18:33:09.107 回答
0

对于 < 5.2 的版本,您必须显式调用 php 魔术函数 __toString()。所以你的代码会变成这样:

    public function myname()
    {
       $name = $this->name;
       return $name.__toString(); //for php versions < 5.2,will also work > 5.2
    }

对于 > 5.2 的版本,会自动调用 __toString

于 2012-10-15T06:50:20.317 回答
0

您需要安装sudo apt install php7.0-mbstring 需要根据您的更改 PHP 版本。

在此之后不要忘记运行service apache2 restart

希望这会有所帮助。

于 2017-01-30T07:05:13.180 回答