问题背景:
PHP脚本有时会抛致命错误,怎么有效的捕获此类异常呢? 一般我们推荐使用PHP的 try...catch... 语句来捕获,
不过本文我们介绍另外一种方法:register_shutdown_function()
函数作用:
PHP中有一个 register_shutdown_function ( callback function [, mixed parameter [, mixed ...]] ) 的函数,其作用是:
1、或在脚本执行完毕后,触发通过 register_shutdown_function预先注册的回调函数。
2、或在脚本中调用了exit()、die()等终止函数时,触发通过 register_shutdown_function预先注册的回调函数。
样板代码:
function shutdownCallback()
{
echo "enter into shutdownCallback...." . PHP_EOL;
print_r(error_get_last());
}
//注册回调函数
register_shutdown_function('shutdownCallback');
//本行 new 会发生致命错误
$object = new notExistClass();
echo 'bye....' . PHP_EOL;
运行结果:
PHP Fatal error: Uncaught Error: Class 'notExistClass' not found in /path/to/demo/shutdown.php:12
Stack trace:
#0 {main}
thrown in /path/to/demo/shutdown.php on line 12
Fatal error: Uncaught Error: Class 'notExistClass' not found in /path/to/demo/shutdown.php:12
Stack trace:
#0 {main}
thrown in /path/to/demo/shutdown.php on line 12
enter into shutdownCallback....
Array
(
[type] => 1
[message] => Uncaught Error: Class 'notExistClass' not found in /path/to/demo/shutdown.php:12
Stack trace:
#0 {main}
thrown
[file] => /path/to/demo/shutdown.php
[line] => 12
)