2017-01-16 35 views
4

我们多年的PHP代码通过set_error_handler()和set_exception_handler()将传统错误转换为异常,从而大量使用异常处理。移植到PHP 7对一些我们的服务器后,像这样的错误,开始抽不出来:将PHP 7错误对象转换为异常?

Uncaught TypeError: Argument 1 passed to DataStellar\General\Exception_Handler::getContext() must be an instance of Exception, instance of Error given 

我们可以用\ Throwable作为类型提示,但大多数的我们的代码库仍然对PHP 5的服务器。

有什么办法可以轻松地将Error对象转换为Exception对象吗?

+0

升级你的服务器或降级你的php版本 – samayo

回答

4

您可以删除方法定义中的类型提示,并使用get_class()instanceof来决定要执行的操作。

class Exception_Handler 
{ 
    public static function getContext($error) 
    { 
     if (class_exists('\\Error') && $error instanceof \Error) { 
      // PHP 7 Error class 
      // handle and return 
     } 

     if ($error instanceof \Exception) { 
      // PHP Exception class (user exception in PHP7) 
      // handle and return 
     } 

     // weird edge case 
    } 
} 
+0

但是Error对象和Exception对象在接口方面是可以相互转换的吗?相同的方法和属性? –

+1

是的,两个实现\ Throwable,只是在PHP7中,你不会得到错误,你只是得到错误对象:http://php.net/manual/en/class.error.php && http://php.net /manual/en/class.exception.php – motanelu

+0

实际上,'\ Throwable'是新的异常基类。 – Andrea