Last active
December 22, 2015 23:49
-
-
Save pdewouters/6549934 to your computer and use it in GitHub Desktop.
This example passes a string value as a parameter to the constructor which expects an array. It catches the error and can decide what to do.
The parameter is required.
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 | |
| /** | |
| * Custom Error Handler for E_RECOVERABLE_ERROR | |
| * | |
| * http://stackoverflow.com/a/2468534/285564 | |
| * | |
| * @param $errno | |
| * @param $errstr | |
| * @param $errfile | |
| * @param $errline | |
| * @return bool | |
| * @throws ErrorException | |
| */ | |
| function myErrorHandler( $errno, $errstr, $errfile, $errline ) { | |
| if ( E_RECOVERABLE_ERROR===$errno ) { | |
| echo "'catched' catchable fatal error\n"; | |
| throw new ErrorException( $errstr, $errno, 0, $errfile, $errline ); | |
| // return true; | |
| } | |
| return false; | |
| } | |
| // Set up the custom error handler | |
| set_error_handler( 'myErrorHandler' ); | |
| /** | |
| * Class Arr_Test | |
| */ | |
| class Arr_Test { | |
| /** | |
| * Gives us a property to play with | |
| * @var array | |
| */ | |
| var $objArr = array(); | |
| /** | |
| * Our object constructor | |
| * @param array $myArr | |
| */ | |
| public function __construct( array $myArr ) { | |
| // Initialize our property to the value of the passed param | |
| $this->objArr = $myArr; | |
| // call a method to test this code | |
| $this->print_myarr(); | |
| } | |
| /** | |
| * Simply iterates an array | |
| */ | |
| protected function print_myarr(){ | |
| for ( $i=0; $i < count( $this->objArr ); $i++) { | |
| echo $this->objArr[$i]; // this would fail if our property is not an array | |
| } | |
| } | |
| } | |
| try { | |
| $my_string_param = 'I will cause an error'; | |
| $myObj1 = new Arr_Test( $my_string_param ); | |
| } catch (Exception $e) { | |
| echo $e->getMessage(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment