2014-11-16 42 views
0

我希望在使用未定义的变量时看到单个错误,但避免发现其他E_NOTICE错误会很好,是否有可能?E_NOTICE:仅报告未定义的变量

+1

大概是用[自定义错误处理程序](http://php.net/manual/en/function.set-error-handler.php)过滤掉你不想要的消息。但其他通知不是您想要解决或能够解决的问题吗? –

+0

你不应该隐藏其他通知。 –

+0

事实上,当我启用E_NOTICE错误时,我的脚本需要几年才能运行,我等了2分钟,然后停下了它(它通常会持续10秒...)。我想这是因为有太多的E_NOTICE错误,并且php永远不会结束,因为它会载入数千个错误。我的脚本非常庞大。 – sylvain1264

回答

2

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

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

您将定义函数在undefined indexundefined variable错误字符串$errstr回调参数中进行字符串匹配。然后,您实际上覆盖了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); 

注意:上述内容不会自动移植到其他英语语言。但是,如果只是为了您自己的目的或有限的使用,那可能不是问题。

+0

使用PHP 5.2.17这段代码不能编译。我想我不能以这种方式使用函数。我在第一行有这个错误:“解析错误:语法错误,意外的T_FUNCTION,期待')'。” – sylvain1264

+0

没关系,你写这个很快有一些错误^^,我可以单独解决这个问题。感谢您的帮助。 – sylvain1264