Skip to content

Instantly share code, notes, and snippets.

@dave1010
Created June 10, 2011 15:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dave1010/1018998 to your computer and use it in GitHub Desktop.
Save dave1010/1018998 to your computer and use it in GitHub Desktop.
How to throw exceptions in a PHP class' __toString method
<?php
class MyClass {
public function __toString() {
try {
return $this->render();
} catch(Exception $e) {
// the __toString method isn't allowed to throw exceptions
// so we turn them into an error instead
trigger_error($e->getMessage() . "\n" . $e->getTraceAsString(), E_USER_ERROR);
return '';
}
}
private function render() {
throw new Exception('Uh oh!');
}
Copy link

ghost commented Apr 30, 2018

or define a ToStringException class that triggers an error on construction, this exception can then be thrown
directly from within __toString

<?php
declare(strict_types=1);

class ToStringException extends Exception
{
    public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
    {
        trigger_error($message, E_USER_ERROR);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment