在错误处理程序中调用 restore_error_handler 可能会导致意外的行为
<?php
error_reporting(0);
set_error_handler('handleError1');
trigger_error('1-stack:h1');
set_error_handler('handleError2');
trigger_error('2-stack:h1,h2');
trigger_error('6-stack:h1,h2');
trigger_error('7-stack:h1,h2');
function handleError1($code, $message, $file = '', $line = 0, $context = array())
{
echo __METHOD__ . ' ' . $message . PHP_EOL;
}
function handleError2($code, $message, $file = '', $line = 0, $context = array())
{
trigger_error('3-DEFAULT'); echo __METHOD__ . ' ' . $message . PHP_EOL;
set_error_handler('handleError3');
trigger_error('4-stack:h1,h2,h3');
restore_error_handler(); trigger_error('5-DEFAULT');
}
function handleError3($code, $message, $file = '', $line = 0, $context = array())
{
echo __METHOD__ . ' ' . $message . PHP_EOL;
}
?>
上面的代码将输出
handleError1 1-stack:h1
handleError2 2-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError1 5-DEFAULT
handleError1 6-stack:h1,h2
handleError1 7-stack:h1,h2
可以使用以下解决方法
<?php
error_reporting(0);
set_error_handler('handleError1');
trigger_error('1-stack:h1');
set_error_handler('handleError2');
trigger_error('2-stack:h1,h2');
trigger_error('6-stack:h1,h2');
trigger_error('7-stack:h1,h2');
function handleError1($code, $message, $file = '', $line = 0, $context = array())
{
echo __METHOD__ . ' ' . $message . PHP_EOL;
}
function handleError2($code, $message, $file = '', $line = 0, $context = [])
{
restore_error_handler(); set_error_handler('count', 0); try
{
trigger_error('3-DEFAULT');
echo __METHOD__ . ' ' . $message . PHP_EOL;
set_error_handler('handleError3');
trigger_error('4-stack:h1,h2,h3');
restore_error_handler();
trigger_error('5-DEFAULT');
}
finally
{
restore_error_handler(); set_error_handler('handleError2'); }
}
function handleError3($code, $message, $file = '', $line = 0, $context = [])
{
echo __METHOD__ . ' ' . $message . PHP_EOL;
}
?>
这将输出
handleError1 1-stack:h1
handleError2 2-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError2 6-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError2 7-stack:h1,h2
handleError3 4-stack:h1,h2,h3