__toString Can Throw Exceptions¶
Until PHP 7.4, the magic method __toString()
could not throw exception, in case of problem occuring during processing.
Since PHP 7.4, it is possible.
PHP code¶
<?php
class X {
function __toString() {
throw new \Exception('error'.__METHOD__);
}
}
(string) new X;
?>
Before¶
PHP Fatal error: Method X::__toString() must not throw an exception, caught Exception: errorX::__toString in /codes/toStringCanThrow.php on line 0
Fatal error: Method X::__toString() must not throw an exception, caught Exception: errorX::__toString in /codes/toStringCanThrow.php on line 0
After¶
PHP Fatal error: Uncaught Exception: errorX::__toString in /codes/toStringCanThrow.php:5
Stack trace:
#0 /codes/toStringCanThrow.php(9): X->__toString()
#1 {main}
thrown in /codes/toStringCanThrow.php on line 5
Fatal error: Uncaught Exception: errorX::__toString in /codes/toStringCanThrow.php:5
Stack trace:
#0 /codes/toStringCanThrow.php(9): X->__toString()
#1 {main}
thrown in /codes/toStringCanThrow.php on line 5
PHP version change¶
This behavior changed in 7.4