考虑以下代码:
class TestClass {
function __construct() {
set_error_handler(array($this,'error_handler'));
}
function error_handler($errno,$errstr,$errfile,$errline,$errcontext) {
trigger_error("\ncode: [$errno]\nfile: [$errfile -> $errline]\nSTR: [$errstr]",E_USER_ERROR);
}
}
count($nonExistentVariable);
//notice was thrown above but script carry on
//but here error handler is registered and...
$anInstance = new TestClass();
// rest of the code is affected by it
count($nonExistentVariable); // user error is thrown
那么,有没有一种方法可以使
error_handler
函数仅在实例内部遇到错误且不会与其他代码全局困惑时才触发?
最佳答案
您可以检查错误处理程序中的调用堆栈(通过debug_backtrace()
),并确定它是否来自您感兴趣的类。如果不是来自该类,请确保为return FALSE
,PHP将转而使用默认的处理程序。
http://php.net/manual/en/function.set-error-handler.php
关于php - 如何设置set_error_handler使其仅在类的实例中生效而不在全局中生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965644/