Skip to content

Instantly share code, notes, and snippets.

@mmacia
Created July 5, 2011 10:31
Show Gist options
  • Save mmacia/1064628 to your computer and use it in GitHub Desktop.
Save mmacia/1064628 to your computer and use it in GitHub Desktop.
How to catch an invalid array index offset as a native exception in PHP
<?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()
{
// override default error handler with our own closure that will detect
// undefined offsets in arrays
set_error_handler(function($errno, $errstr, $errfile, $errline) {
// we are only interested in 'undefined index/offset' errors
if (strpos($errstr, 'Undefined offset') !== false) {
throw new OutOfRangeException($errstr, 0);
}
return true; // error bublling to PHP's default handler
});
}
public function __destruct()
{
// very important, restore the default error handler whe finish
restore_error_handler();
}
public function m()
{
$matrix[1][1] = 'dfsdf';
$matrix[1][0] = 'dfsdf';
$matrix[0][1] = 'dfsdf';
try {
echo $matrix[0][0]; // this offset doesn't exists!
}
catch(OutOfRangeException $e) {
echo "exception catched!\n";
}
}
}
$a = new A();
$a->m(); // out -> Exception catched!
unset($a);
$matrix = array();
echo $matrix[0][0]; // out -> default PHP error message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment