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

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

Leave a Comment