Is there a php.ini setting or some other trick to force PHP to produce a fatal error or similar when an undefined constant is used, rather than the (ridiculous) default behavior of assuming a string of the same name?
The default behavior can be a gaping security risk, but more often than not it just leads to application errors. I realize that I can use defined()
to check the existence of the constant prior to asking for the value, but this leads to redundant/ugly code, and is still prone to developer error. We're very careful about ensuring that used constants are defined, but this problem still sneaks into production once in a while, and I'd like to prevent it if possible. A fatal error would be more "in your face" and much less likely to squeeze by QA.
Constants are like variables except that once they are defined they cannot be changed or undefined.
Code Inspection: Undefined constantReports the references to constants that are not found in the project files, configured include paths, or among the PHP predefined constants.
PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways: Using define() function. Using const keyword.
A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.
set_error_handler(function($type, $error) {
if(stripos($error, 'Use of undefined constant') !== FALSE)
{
// god forbid - someone's used an undefined constant. Act appropriately.
trigger_error($error, E_USER_ERROR); // Triggers a fatal error.
return TRUE;
}
}, E_NOTICE);
This is maybe what you're looking for, as far as I'm aware there's no way to modify PHP's error 'ranking'.
Undefined constants generate a PHP notice.
You can just throw an exception for any PHP warning, at least in development mode:
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 1, $errfile, $errline);
// or turn it in a fatal error
trigger_error($errstr, E_USER_ERROR);
});
If you want to handle only undefined constant
warnings, test if the $errstr
matches against Use of undefined constant FOO - assumed 'FOO'
.
Note: only unqualified, global constants behave like this. PHP throws a fatal error for undefined class constants and undefined namespaced constants (e.g. Foo::BAR
or Foo\BAR
).
So if you want PHP to throw fatal errors when using undefined constants, an other solution is to use class constants or namespaced constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With