Calling restore_error_handler from within an error handler might result in unexpected behaviour:
<?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;
}
?>
The above code will output:
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
The following workaround can be used:
<?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;
}
?>
which will output:
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