PHP 7.4 中无法捕获弃用警告

Deprecation warning not catchable in PHP 7.4

在 PHP 7.4.0 中,我看到以下警告:
Deprecated: Array and string offset access syntax with curly braces is deprecated in ...
我的错误/异常处理程序无法捕获并记录它们。

示例:

<?php
    set_error_handler(function ($errNo, $errStr) {
        echo "set_error_handler: " . $errStr;
    });

    set_exception_handler(function ($exception) {
        echo "set_exception_handler: " . $exception->getMessage();
    });

    $b = 'test';
    $a = $b{1};

警告仍然显示在正常输出中并调用了两个处理程序的none。

我想在我自己的日志中记录所有错误、异常和警告,但处理程序未捕获此警告。是否有此原因或解决方案来捕获和记录 PHP 抱怨的所有内容(无法访问服务器 Apache/PHP 日志)?

set_error_handler 根据文档捕获在 运行 时间发出的消息:

This function can be used for defining your own way of handling errors during runtime

您看到的弃用警告是 implemented at compile-time,根据定义,它发生在 运行 时间之前:

static zend_op *zend_delayed_compile_dim(znode *result, zend_ast *ast, uint32_t type) /* {{{ */
{
    if (ast->attr == ZEND_DIM_ALTERNATIVE_SYNTAX) {
        zend_error(E_DEPRECATED, "Array and string offset access syntax with curly braces is deprecated");
    }
    ...

您可能会认为它是 "soft syntax error":它是在解析时发现的,在编译步骤中,但它不是一个严重的致命问题,而是对未来厄运的警告。与语法错误一样,您有两种处理方式:前置处理和关闭处理。

前置

$ cat error-handler.php
<?php
set_error_handler(fn(...$args) => var_dump($args));
$ cat try.php
<?php
$b = 'test';
$a = $b{1};
$ php -d auto_prepend_file=error-handler.php try.php
array(5) {
  [0]=>
  int(8192)
  [1]=>
  string(69) "Array and string offset access syntax with curly braces is deprecated"
  [2]=>
  string(21) "/Users/bishop/try.php"
  [3]=>
  int(3)
  [4]=>
  NULL
}

关机处理

register_shutdown_function(fn() => var_dump(error_get_last()));

$b = 'test';
$a = $b{1};

输出:

array(4) {
  ["type"]=>
  int(8192)
  ["message"]=>
  string(69) "Array and string offset access syntax with curly braces is deprecated"
  ["file"]=>
  string(9) "/in/212CF"
  ["line"]=>
  int(7)
}

使用哪个?

根据您的需要选择一个或两个。就我个人而言,我使用前置方法,因为它可以处理各种其他白屏死机场景。如果您在网络上下文中执行此操作,则需要安排您的网络服务器来设置 auto_prepend_file 设置:一旦您的 "main" 代码为 运行ning,您就无法设置前置并让它像这里演示的那样工作。