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
升级 PHP
我正在处理相同的问题,我怀疑你最好的选择是将生产服务器上的 PHP 升级到 >= 5.2.0
在未来(我目前正在通过艰难的方式学习这一点),请尝试在开发和部署时使用相同的版本。
您需要安装 sudo apt install php7.0-mbstring
,根据您的需求更改PHP版本。
之后不要忘记运行 service apache2 restart
希望这能帮到您。
public function myname()
{
$name = $this->name;
return $name.__toString(); //for php versions < 5.2,will also work > 5.2
}
对于版本大于5.2的情况,__toString会自动调用
$name->__toString();
。 - Erik Kaplun