gpt4 book ai didi

php - 为什么无法从 __toString() 中抛出异常?

转载 作者:IT王子 更新时间:2023-10-29 00:01:01 25 4
gpt4 key购买 nike

为什么不能从 __toString() 抛出异常?

class a
{
public function __toString()
{
throw new Exception();
}
}

$a = new a();
echo $a;

上面的代码产生了这个:

Fatal error: Method a::__toString() must not throw an exception in /var/www/localhost/htdocs/index.php on line 12

我被指向 http://php.net/manual/en/migration52.incompatible.php在哪里描述了这种行为,但为什么?有什么理由这样做吗?

这里有人知道吗?

在错误跟踪器 php-dev-team 中,除了查看手册之外什么也没说:http://bugs.php.net/50699

最佳答案

经过几次搜索,我发现了这个,上面写着:

Johannes explained that there is no way to ensure that an exception thrown during a cast to string would be handled correctly by the Zend Engine, and that this won't change unless large parts of the Engine are rewritten. He added that there have been discussions about such issues in the past, and suggested that Guilherme check the archives.

Johannes上面引用的是 PHP 5.3 发布管理器,因此它可能是您可能会发现的关于 PHP 为何会以这种方式运行的“官方”解释。

该部分继续提到:

__toString() will, strangely enough, accept trigger_error().

因此,在 __toString() 中的错误报告方面,并非所有内容都丢失了。

关于php - 为什么无法从 __toString() 中抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com