Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save th-yoo/7c8195de080484b07de4517ac12335dd to your computer and use it in GitHub Desktop.
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)
<?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á <mmacia@gmail.com>
* @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