CodeIgniter CI_Exceptions::show_exception 更新到 PHP 7 后出错

CodeIgniter CI_Exceptions::show_exception error after updating to PHP 7

我在 PHP 5.6 中使用 CodeIgniter 3.0.0。

昨天我更新到 PHP 7 并开始出现以下错误:-

Uncaught TypeError: Argument 1 passed to CI_Exceptions::show_exception() must be
 an instance of Exception, instance of Error given, called in /my/file/path/app/system/core/Common.php on line 658 and defined in /my/file/path/hgx_portal/app/system/core/Exceptions.php:190
Stack trace:
#0 /my/file/path/hgx_portal/app/system/core/Common.php(658): CI_Exceptions->show_exception(Object
(Error))
#1 [internal function]: _exception_handler(Object(Error))
#2 {main}
  thrown in /my/file/path/hgx_portal/app/system/core/Exceptions.phpon line 190

这是 CodeIgniter 3.0.0 中的已知问题,请参阅下面的 github 问题 here and changelog

Fixed a bug (#4137) - :doc:Error Handling <general/errors> breaks for the new Error exceptions under PHP 7.

因为 set_exception_handler() changed behavior 在 PHP 7.

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

升级到 3.0.2 之后的任何版本都可以解决您的问题。

此错误是由 PHP 7(在 set_exception_handler 函数中抛出 Error 而不是 Exception 引起的。

如果您无法升级 CodeIgniter 系统文件夹,您可以只更改 system/core/Exceptions.php 行的文件 190:

public function show_exception(Exception $exception)

public function show_exception($exception)

直接去/system/core/Exceptions.php 打开文件,然后'save'

对我有用

我使用 macOS Monterey,PHP 8.1.2