How to make PHP undefined constants notice an error
I just spent hours trying to debug an out of memory error caused by the following code:
for ($i = 1; i <= 4; $i++) {
$allowed[] = $type.'_'.$i;
}
Which PHP kindly mangles into:
for ($i = 1; 'i' <= 4; $i++) {
$allowed[] = $type.'_'.$i;
}
This causes an endless loop, which eventually leads to an out of memory error due to appending to the array. PHP will generate a notice level error, and I could change my error reporting level to show these but I am working on a third party application which has a tendency to generate enough of these that 开发者_如何学编程this isn't really a viable solution.
Is there any way to trap these really simple bugs? Ironically, if you do something like constant('i')
and explicitly ask for the value it will generate a warning rather than a notice, and this behaviour would be ideal.
You could create a custom error function then filter out the most common errors and only report the less common ones. Then up the error reporting level in PHP. E.g.
function customError($error_no, $error_message, $error_file, $error_line, $error_context) {
$common_errors = Array('File not found', 'Another made up error', 'Its late');
if (! in_array($error_message, $common_errors)) {
// throw exception, log to file, or other action
}
}
set_error_handler("customError");
You could also filter errors like so:
Filter out all errors unless they are in a file of interest by testing
$error_file
against an array of files you maintainEven better (not on a production server) fetch the last_modified date/time of
$error_file
withfilemtime()
and report the error if it was changed within the last 10 minutes. This helps you debug code as you write itOr if it's within a framework which yours sounds like it is, break apart the path of
$error_file
and test if it's in your module/view/controller files, as opposed to core framework files
In PHP 7.2 this notice has been changed to a warning.
In PHP 8.0 it will be an error.
精彩评论