Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将PHP7错误对象转换为异常?_Php_Exception_Php 7 - Fatal编程技术网

将PHP7错误对象转换为异常?

将PHP7错误对象转换为异常?,php,exception,php-7,Php,Exception,Php 7,我们多年的PHP代码大量使用异常处理,通过set_error_handler()和set_Exception_handler()将传统错误转换为异常。在为我们的一些服务器迁移到PHP 7之后,出现了如下错误: Uncaught TypeError: Argument 1 passed to DataStellar\General\Exception_Handler::getContext() must be an instance of Exception, instance of Error

我们多年的PHP代码大量使用异常处理,通过set_error_handler()和set_Exception_handler()将传统错误转换为异常。在为我们的一些服务器迁移到PHP 7之后,出现了如下错误:

Uncaught TypeError: Argument 1 passed to DataStellar\General\Exception_Handler::getContext() must be an instance of Exception, instance of Error given
我们可以使用\Throwable作为类型提示,但我们的大多数代码库仍然在PHP5服务器上


这里有什么方法可以轻松地将错误对象转换为异常对象吗?

您可以从方法的定义中删除类型提示,然后使用
get\u 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
    }
}

升级您的服务器,或降级您的php版本,但是错误对象和异常对象在接口方面是相互可变的吗?相同的方法和属性?是的,都实现了\Throwable,只是在PHP7中没有错误,只有错误对象:&&实际上,
\Throwable
是新的异常基类。