Last active
April 19, 2016 14:31
-
-
Save jeremeamia/9744455 to your computer and use it in GitHub Desktop.
Handle undefined constants in PHP with set_error_handler()
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 | |
set_error_handler(function ($errNo, $errStr) { | |
if (strpos($errStr, 'Use of undefined constant ') === 0) { | |
$constant = strstr(substr($errStr, 26), ' ', true); | |
define($constant, $constant); | |
} else { | |
return false; | |
} | |
}, E_NOTICE); | |
echo FOO . "\n"; | |
echo "BAR\n"; | |
// Note: Unfortunately, missing constants referenced with a namespace or class | |
// qualifier trigger non-catchable, fatal (E_ERROR) errors instead of E_NOTICE. |
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 | |
set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { | |
echo "UH OH!\n"; | |
die; | |
}); | |
function set_missing_constant_handler($handler) | |
{ | |
$prevErrorHandler = set_error_handler( | |
function ($errno, $errstr, $errfile, $errline, $errcontext) use ($handler, &$prevErrorHandler) { | |
if (!strpos($errstr, 'Use of undefined constant ') === 0) { | |
$constant = strstr(substr($errstr, 26), ' ', true); | |
$handler($constant); | |
} elseif ($prevErrorHandler) { | |
$prevErrorHandler($errno, $errstr, $errfile, $errline, $errcontext); | |
} else { | |
return false; | |
} | |
}, | |
E_NOTICE | |
); | |
} | |
set_missing_constant_handler(function($constant) { | |
define($constant, $constant); | |
}); | |
echo FOO . "\n"; | |
echo "BAR\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment