Throwing exceptions from __toString() is currently forbidden and will result in a fatal error. This makes it dangerous to call arbitrary code inside __toString() and makes its use as a general API problematic. This RFC aims to remove this restriction.

The rationale for the current behavior is that string conversions are performed in many places throughout the engine and standard library, and not all places are prepared to deal with exceptions “correctly”, in the sense that the exception is handled as early as possible.

This limitation is ultimately futile from a technical perspective, because exceptions during string conversion can still be triggered by an error handler that converts recoverable errors to exceptions:

set_error_handler ( function ( ) { throw new Exception ( ) ; } ) ; try { ( string ) new stdClass ; } catch ( Exception $e ) { echo "(string) threw an exception...

" ; }

In fact, Symfony uses this loophole to work around the current limitation. Unfortunately this relies on the $errcontext parameter, which is going away in PHP 8.

Despite this, the sentiment in past discussions on this topic has been to not relax this restriction until we have performed a comprehensive audit of string conversions across the codebase. This has been done in the attached implementation pull request.