在php5的版本中,如果出現(xiàn)致命錯誤是無法被 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()
有些時候,我們需要捕獲這種錯誤,并做相應(yīng)的處理。
那就需要用到?register_shutdown_function() 和?error_get_last() 來捕獲錯誤
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
//注冊一個會在php中止時執(zhí)行的函數(shù)
register_shutdown_function(function () {
//獲取最后發(fā)生的錯誤
$error = error_get_last();
if (!empty($error)) {
echo $error['message'], '<br>';
echo $error['file'], ' ', $error['line'];
}
});
hello();
對于php7中的錯誤捕獲,因為php7中定義了 Throwable 接口,大部分的 Error 和 Exception 實現(xiàn)了該接口。文章來源:http://www.zghlxwxcb.cn/news/detail-827983.html
所以我們在php7中,可以通過 try {} catch(\Throwable $e) 來捕獲php5中無法捕獲到的錯誤。文章來源地址http://www.zghlxwxcb.cn/news/detail-827983.html
到了這里,關(guān)于php捕獲Fatal error錯誤與異常處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!