处理PHP的致命错误(Fatal Error 或 E_ERROR)

如何处理PHP的E_ERROR或Fatal Error是一件麻烦事。当程序因为内存不足、执行超时等等而出现致命错误意外中断时,也需要进行相关的处理,而这时error_reporting与try...catch都不适用。

这时可以利用PHP的register_shutdown_function函数。

手册上写的很明确:register_shutdown_function — Register a function for execution on shutdown,就是说当程序中断时会调用该函数注册的函数。

比如:

<?php
function shutdown() {
echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');
?>


当然,任何的程序中断都会触发用此方法注册的函数,包括exit()等等。如果想只用来处理某段程序的致命错误,这时需要进行一下判断,可以参考一下代码:


<?php
class Test {
private $running;

public function __construct() {
register_shutdown_function(array($this, 'shutdown_handler'));
}

public function main() {
$this->running = true; //开始监测
echo "Hello ";
$this->error(); //(undefined method)触发一个致命错误
echo "World ";
$this->running = false; //结束监测
}

public function shutdown_handler() {
if ($this->running) {
echo '抱歉出错了~';
@header("Location: error.php");
}
}
}

$t = new Test();
$t->main();
?>


更新:其实这里可以使用error_get_last()函数来获取最后一条错误

<?php
public function shutdown_handler() {
$error = error_get_last();
if ($error['type'] == 1) { //只针对E_ERROR
echo '抱歉出错了~';
@header("Location: error.php");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值