Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__toString Can Throw Exceptions

The magic method __toString() could not throw exception, in case of problem occurring 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

Fatal error: Method X::__toString() must not throw an exception, caught Exception: errorX::__toString

After

PHP Fatal error:  Uncaught Exception: errorX::__toString

Fatal error: Uncaught Exception: errorX::__toString

PHP version change

This behavior changed in 7.4.

Error Messages

Extension

Analyzer

© 2023-2026, Damien Seguy - Exakat