使用连接时不调用php toString


php toString not called when concatenate is used

引用php 5.1.6 magic __toString方法

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

PHP & lt;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()

我应该重写哪些其他方法要使对象在string concatates/etc

上下文中正确显示

当前,我得到类似

的内容
echo 'Hello ' . $yourObject;

生成'Hello Object ID 55';

谁有解决方案的上下文中:

  • 客户端不希望升级php版本
  • 不要到处乱溅__toString

?

您是否阅读了PHP文档中的免责声明?

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

因为你没有直接涉及对象的回显(即你正在做一个连接操作首先),__toString方法不会被调用。所以要么升级你的PHP版本,要么显式调用__toString