Created
June 10, 2011 15:02
-
-
Save dave1010/1018998 to your computer and use it in GitHub Desktop.
How to throw exceptions in a PHP class' __toString method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or define a ToStringException class that triggers an error on construction, this exception can then be thrown
directly from within __toString