编程

PHP 8.5: 新增 get_exception_handler 和 get_error_handler 函数

17 2025-05-20 03:33:00

PHP 允许设置自定义错误和异常处理程序(error/exception handler),当触发错误或异常未被捕获时会调用这些处理程序。同时可以恢复之前的异常和错误处理程序。

然而,在 PHP 8.5 之前,没有直接的方法来获取当前设置的错误和异常处理程序。PHP 8.5 添加了两个函数-- get_error_handlerget_exception_handler,它们提供了此功能。

设置错误和异常处理程序

set_error_handler('my_custom_error_handler_function');
set_exception_handler('my_custom_exception_handler_function');

当设置错误及异常处理程序时,set_*_handler 函数的调用将返回现有的错误处理程序。

新增 get_error_handler 函数

PHP 8.5 添加了一个新的函数 get_error_handler,它返回当前激活的错误处理程序:

/**
 * Returns the currently set error handler, or null if none is set.
 * @return callable|null
 */
function get_error_handler(): ?callable {}

用例

如果没有设置错误处理程序,调用 get_error_handler 将返回 null

get_error_handler(); // null

而当设置自定义错误处理程序后,get_error_handler 将返回这一 callable

set_error_handler(fn() => null);
get_error_handler(); // object(Closure)#1 (3) {...}

新增 get_exception_handler 函数

PHP 8.5 中新增的 get_exception_handler 函数类似于 get_error_handler 函数。它返回当前设置的异常处理程序,如果未设置异常处理程序则返回 null

/**
 * Returns the currently set exception handler, or null if none is set.
 * @return callable|null
 */
function get_exception_handler(): ?callable {}

用例

如果未设置异常处理程序,调用 get_exception_handler 将返回 null:

get_error_handler(); // null

而当设置自定义错误处理程序后,get_exception_handler 将返回这一 callable

set_error_handler(fn() => null);
get_error_handler(); // object(Closure)#1 (3) {...}

PHP Polyfill

因为 set_error_handlerset_exception_handler 函数返回的是当前 handler,可以使用 PHP 轻松地对这些函数进行 polyfill:

/**
 * Returns the currently set error handler, or null if none is set.
 * @return callable|null
 */
function get_error_handler(): ?callable {
    $handler = set_error_handler(null);
    restore_error_handler();

    return $handler;
}

/**
 * Returns the currently set exception handler, or null if is none set.
 * @return callable|null
 */
function get_exception_handler(): ?callable {
    $handler = set_exception_handler(null);
    restore_exception_handler();

    return $handler;
}

向后兼容性影响

get_error_handlerget_exception_handler 是 PHP 8.5 引入的新函数。除非现有的 PHP 应用在全局命名空间中声明了同样的函数名,这个改变不会造成向后兼容性影响。

此外,也可以对这两个函数进行 polyfill。

 

下一篇