2014-10-05 142 views
5

有没有一种方法可以告诉PHP在我试图访问null对象上的成员或方法时抛出异常?PHP处理异常空处理

例如为:

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

现在,我只得到了下面的错误不属于很好的处理:

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 ... 

我想有而不是抛出一个特定的异常。这可能吗?

+0

注册一个[全局错误处理程序](http://php.net/manual/en/function.set-error-handler.php)并抛出你自己的异常。 – Rob 2014-10-05 16:16:21

回答

3

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

致命错误不能转化为例外,他们是专为PHP停止尽快。但是,我们可以通过做使用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"; 
} 
1

所包含或其他任何东西之前执行的文件中添加以下代码一些最后一分钟的处理妥善处理胎儿的错误:

set_error_handler(
    function($errno, $errstr, $errfile, $errline) { 
     throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); 
    } 
); 
2

试试这个代码来捕获全部错误:

<?php  
$_caughtError = false; 

register_shutdown_function(
     // handle fatal errors 
     function() { 
      global $_caughtError; 
      $error = error_get_last(); 
      if(!$_caughtError && $error) { 
       throw new \ErrorException($error['message'], 
              $error['type'], 
              2, 
              $error['file'], 
              $error['line']); 
      } 
     } 
); 

set_error_handler(
    function($errno, $errstr, $errfile, $errline) { 
     global $_caughtError; 
     $_caughtError = true; 
     throw new \ErrorException($errstr, $errno, 1, $errfile, $errline); 
    } 
); 

它应该被执行或包含在其他代码之前。

你也可以实现一个Singleton来避免全局变量,或者让它抛出两个异常,如果你不介意的话。