Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

exception

php

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

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

the code above produces this:

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

I was pointed to http://php.net/manual/en/migration52.incompatible.php where this behavior is described, but why? Any reasons to do that?

May be anyone here knows this?

At bug tracker php-dev-team as usual says nothing but see manual: http://bugs.php.net/50699

like image 310
zerkms Avatar asked Mar 12 '10 00:03

zerkms


2 Answers

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

like image 118
Rob Hruska Avatar answered Oct 07 '22 19:10

Rob Hruska


My guess would be that __toString is hackish and therefore exists outside of the typical stack. A thrown exception, then, wouldn't know where to go.

like image 42
Matchu Avatar answered Oct 07 '22 18:10

Matchu