PHP通过异常处理null处理 [英] PHP handle null handling by exception

查看:143
本文介绍了PHP通过异常处理null处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试访问 null 对象上的成员或方法时,是否可以告诉PHP引发异常?

Is there a way I can tell PHP to throw an exception when I am trying to access a member or method on a null object?

例如:

$x = null;
$x->foo = 5; // Null field access
$x->bar(); // Null method call

现在,我只收到以下不好处理的错误:

Right now, I only get the following errors which are not nice to handle:

PHP Notice:  Trying to get property of non-object in ...
PHP Warning:  Creating default object from empty value in ...
PHP Fatal error:  Call to undefined method stdClass::bar() in ...


中调用未定义的方法stdClass :: bar()

我想抛出一个特定的异常。

I would like to have a specific exception being thrown instead. Is this possible?

推荐答案

您可以使用 set_error_handler(),因此,每当发生警告时,它将生成一个异常,您可以在try-catch块中捕获该异常。

You can turn your warnings into exceptions using set_error_handler() so when ever an warning occurs, it will generate an Exception which you can catch in a try-catch block.

致命错误无法转化为异常,它们是为php尽快停止而设计的。但是,我们可以通过使用 register_shutdown_function( )

Fatal errors can't be turned into Exceptions, they are designed for php to stop asap. however we can handle the fetal error gracefully by doing some last minute processing using register_shutdown_function()

<?php

//Gracefully handle fatal errors
register_shutdown_function(function(){
    $error = error_get_last();
    if( $error !== NULL) {
        echo 'Fatel Error';
    }
});

//Turn errors into exceptions
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try{
    $x = null;
    $x->foo = 5; // Null field access
    $x->bar(); // Null method call
}catch(Exception $ex){
    echo "Caught exception";
}

这篇关于PHP通过异常处理null处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆