Skip to content

Instantly share code, notes, and snippets.

@jeremeamia
Last active April 19, 2016 14:31
Show Gist options
  • Save jeremeamia/9744455 to your computer and use it in GitHub Desktop.
Save jeremeamia/9744455 to your computer and use it in GitHub Desktop.
Handle undefined constants in PHP with set_error_handler()
<?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.
<?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