2017-01-16 55 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