PHP7以上的异常处理变化

2021年7月19日10:37:39

https://www.php.net/manual/zh/class.throwable

PHP 7 里,Throwable 是能被 throw 语句抛出的最基本的接口(interface),包含了 Error 和 Exception

注意这里error和exception都是实现Throwable 接口,所以在要捕获error和exception,就可以直接捕获Throwable 

demo

try {

    throw new Error('error');
    throw new Exception('exception');

} catch (Throwable $t) {
    p($t);
}

如果需要自定义异常错误全局捕捉

set_error_handler('zx_error');
set_exception_handler('zx_exception');
ini_set("display_errors", "off");
error_reporting(E_ALL);

function zx_error($errno, $errstr, $errfile, $errline)
{
    p($errno);
    p($errstr);
    p($errfile);
    p($errline);
}


function zx_exception($exception)
{
    p($exception);
}

需要注意的地方,在PHP7以下的是不能在逻辑代码里捕捉error的,只能在set_error_handler里面全局捕捉

所以如果你的 项目可以上PHP7的建议就上,值得主要的点有两个,1,PHP7以上的性能比php7一下的增长30%以上,2,虽然PHP不是一个注重语法糖的语言,但是一些便利性的语法糖,在php以上有很多改变

QQ群 247823727 博客文件如果不能下载请进群下载
如果公司项目有技术瓶颈问题,如有需要,请联系我,提供技术服务 QQ: 903464207
原文地址:https://www.cnblogs.com/zx-admin/p/15029166.html