E_NOTICE: Report only undefined variables

178 views Asked by At

I would like to see a single error when I am using an undefined variable, but it would be nice to avoid to see other E_NOTICE errors, is it possible ?

1

There are 1 answers

2
Michael Berkowski On BEST ANSWER

Officially I would recommend against doing this, as it is quite possible to write PHP code that generates no warnings or notices. Indeed that should be your goal - to eliminate all notices and warnings.

However, what you're asking would be possible to achieve using PHP's custom error handling via set_error_handler(), which accepts a callback function to run when an error is issued.

You would define the function to do string matching for undefined index and undefined variable in the error string $errstr callback parameter. You are then in effect overriding PHP's normal error reporting system, and substituting your own. I would reiterate that I don't think this is a great solution.

$error_handler = function($errno, $errstr, $errfile, $errline) {
  if (in_array($errno, array(E_NOTICE, E_USER_NOTICE))) {
    // Match substrings "undefined index" or "undefined variable"
    // case-insensitively. This is *not* internationalized.
    if (stripos($errstr, 'undefined index') !== false || stripos($errstr, 'undefined variable') !== false) {
       // Your targeted error - print it how you prefer
       echo "In file $errfile, Line $errline: $errstr";
    }
  }
};

// Set the callback as your error handler
// Apply it only to E_NOTICE using the second parameter $error_types
// so that PHP handles other errors in its normal way.
set_error_handler($error_handler, E_NOTICE);

Note: The above is not automatically portable for languages other English. But if it is only for your own purposes or limited use, that's maybe not a problem.