在php5的版本中,如果出现致命错误是无法被 try {} catch 捕获的,如下所示:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
try {
hello();
} catch (\Exception $e) {
echo $e->getMessage();
}
运行脚本,最终php报出一个Fatal error,并程序中止
Fatal error: Uncaught Error: Call to undefined function hello()
有些时候,我们需要捕获这种错误,并做相应的处理。
那就需要用到 register_shutdown_function() 和 error_get_last() 来捕获错误
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
//注册一个会在php中止时执行的函数
register_shutdown_function(function () {
//获取最后发生的错误
$error = error_get_last();
if (!empty($error)) {
echo $error['message'], '<br>';
echo $error['file'], ' ', $error['line'];
}
});
hello();
对于php7中的错误捕获,因为php7中定义了 Throwable 接口,大部分的 Error 和 Exception 实现了该接口。
所以我们在php7中,可以通过 try {} catch(\Throwable $e) 来捕获php5中无法捕获到的错误。