note 120878 deleted from function.restore-error-handler by cmb
| From: | cmb@php.net | Date: | Mon, 27 Mar 2017 14:44:54 +0000 |
| Subject: | note 120878 deleted from function.restore-error-handler by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208954@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
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'); // This will use the php's default error handler
echo __METHOD__ . ' ' . $message . PHP_EOL;
set_error_handler('handleError3');
trigger_error('4-stack:h1,h2,h3');
restore_error_handler(); // This will restore the handleError1 instead of the default 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(); // This will restore the previous error handler
set_error_handler('count', 0); // Set a dummy method for error handling, it will never be
called because $error_type = 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(); // Restore the previous error handler
set_error_handler('handleError2'); // Set the current error handler again
}
}
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