In PHP, Exception::__toString() returns a string representation of the exception. It usually includes the class name, message, code, file, line, and stack trace.
PHP calls __toString() when you use the exception as a string, for example with echo $e or in string interpolation. Unlike most getters, subclasses may override __toString() to change the format.
Syntax
Call __toString() with the values you need. Start with this line.
PHP
echo $e;
Call
What it does
(string) $e
Casts the exception to a string and calls __toString().
echo $e;
Prints the full exception string, including the stack trace.
$e->__toString()
Calls the method directly; usually not needed.
__toString() can be overridden in a subclass. The default Exception version includes message details and the stack trace string.
Library declarations
PHP
public Exception::__toString(): string
Parameters
Parameter
Description
—
This method takes no parameters.
Return Value
Return Value
Description
string
A readable summary of the exception, typically including the stack trace.
PHP Examples
Example 1 — Echo an Exception
Catch an Exception and print it with echo, which calls __toString().