Why it's impossible to throw exception from __toString()?

后端 未结 6 1896
半阙折子戏
半阙折子戏 2020-12-29 18:33

Why it\'s impossible to throw exception from __toString()?

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

$a = new          


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 18:53

    After a couple searches I found this, which says:

    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.

    The Johannes referenced above is the PHP 5.3 Release Manager, so it's probably as "official" an explanation as you might find as to why PHP behaves this way.

    The section goes on to mention:

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

    So not all is lost in terms of error reporting within __toString().

提交回复
热议问题