E_NOTICE:仅报告未定义的变量


E_NOTICE: Report only undefined variables

我希望

在使用未定义的变量时看到单个错误,但最好避免看到其他E_NOTICE错误,可以吗?

正式地,我建议不要这样做,因为很有可能编写不生成警告或通知的PHP代码。事实上,这应该是您的目标 - 消除所有通知和警告。

但是,您所要求的可以通过 PHP 的自定义错误处理来实现 set_error_handler() ,它接受在发出错误时运行的回调函数。

您将定义函数以在错误字符串$errstr回调参数中对undefined indexundefined variable进行字符串匹配。然后,您实际上覆盖了PHP的正常错误报告系统,并替换了自己的错误报告系统。 我要重申,我认为这不是一个很好的解决方案。

$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);

注意:对于英语以外的语言,上述内容不会自动移植。但如果它只是为了你自己的目的或有限的用途,那可能不是问题。