php有提供
set_error_handler
用来自定义一个错误处理机制.需要注意的是:
<php manual中>
It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately.
然而没有提供一个恢复到默认的error handler.尽管:
restore_error_handler可以恢复到上一个error handler,php manual中是如此说明的:
Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).
问题来了,那是不是说<连续>调用两次是不是等没调用.事实不是这样的,我从在线文档的例子解释中了解到它采用的是一个堆栈的结构,结合数据结构课本restore_error_handler应该是从堆栈中弹出一个元素,而不是类似注册模式那样在两个值之间toggle.
看例子就会理解清楚了:
<?php
function custom_error_handler(){
echo 'My error handler';
return false;
}
set_error_handler('custom_error_handler'); // Stack is: <default error handler> | custom_error_handler
set_error_handler('custom_error_handler'); // Stack is: <default error handler> | custom_error_handler | custom_error_handler
trigger_error('error', E_USER_WARNING); // Will print 'My error handler';
restore_error_handler(); // The stack is <default error handler> | custom_error_handler
trigger_error('error', E_USER_WARNING); // Will still print 'My error handler', since the stack is still dirty with our first custom_error_handler.
restore_error_handler(); // The stack is <default error handler>
trigger_error('error', E_USER_WARNING); // Now this will trigger the default error handler.
?>
参考: