Forked from mmacia/test_undefined_offset_exception.php
Last active
September 1, 2019 11:48
-
-
Save th-yoo/7c8195de080484b07de4517ac12335dd to your computer and use it in GitHub Desktop.
How to catch an invalid array index offset as a native exception in PHP (RAII supported)
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 | |
/** | |
* this class shows how to override default PHP handler to catch undefined index errors | |
* and throw it as native exceptions, much more convenient way to work with object | |
* oriented programs. | |
* | |
* @author Moisés Maciá <[email protected]> | |
* @see http://codeup.net | |
*/ | |
class A { | |
public function __construct() | |
{ | |
echo "CTOR\n"; | |
// override default error handler with our own closure that will detect | |
// undefined offsets in arrays | |
// | |
// Error handler should not be a closure | |
// if we want to expect RAII, | |
// i.e., to call the dtor automatically at the end of a scope. | |
// A closure defined in a regular member function | |
// captures '$this' reference. | |
// The captured $this prevents from calling the dtor | |
// becasue the life scope of the captured $this reference | |
// is the same as the closure. | |
// This is why we define the error handler as a static function. | |
set_error_handler('A::error_handler'); | |
} | |
public function __destruct() | |
{ | |
// very important, restore the previous error handler when finish | |
restore_error_handler(); | |
echo "DTOR\n"; | |
} | |
public static function error_handler($errno, $errstr, $errfile, $errline) | |
{ | |
// we are only interested in 'undefined index/offset' errors | |
if (preg_match("/^Undefined offset|index/", $errstr)) { | |
throw new OutOfRangeException($errstr); | |
} | |
return FALSE; // If the function returns FALSE then the normal error handler continues. | |
} | |
} | |
function exception_needed_function() | |
{ | |
// exception available only in this scope | |
$IndexErrorAsException = new A(); | |
$matrix = []; | |
try { | |
return $matrix[0][0]; | |
} | |
catch (OutOfRangeException $e) { | |
echo "OutOfRangeException caught\n"; | |
} | |
} | |
function exception_unneeded_function() | |
{ | |
$matrix = []; | |
return $matrix[0][0]; | |
} | |
exception_needed_function(); | |
echo "---------------------------\n"; | |
exception_uneeded_function(); | |
echo "End of scrypt\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment