【问题标题】:Too few arguments to function exception_error_handler() - PHP8函数 exception_error_handler() 的参数太少 - PHP8
【发布时间】:2021-03-19 21:57:54
【问题描述】:

标题怎么说,这个错误发生在我身上。 我在互联网上搜索并发现 https://github.com/processwire/processwire-issues/issues/1286#issuecomment-738880424

原码:

function exception_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
}

我只是更改了最后一个参数并使其成为可选参数:

function exception_error_handler($errno, $errstr, $errfile, $errline, $errcontext=[]) {
}

有人知道为什么这个参数变成可选的吗?

【问题讨论】:

  • 在哪里您更新了最后一个参数?
  • manual 自 PHP7.2.0 起 errcontext 已弃用。现在使用此参数会发出 E_DEPRECATED 通知。 (强烈建议不要使用)
  • 有人知道为什么这个参数变成可选的吗? php.net/manual/en/…

标签: php php-8


【解决方案1】:

这里对于什么是可选的以及为什么存在一些混淆。

您定义的函数是一个回调函数,PHP 将使用某些参数调用它,are documented in the manual。 (请注意,在提问时,该页面使用了不同的措辞;写完此答案后,I submitted a patch updating it for PHP 8.0 and hopefully making it clearer)。

根据文档,旧版本的 PHP 将 5 个参数传递给回调,接收第 5 个参数:

在触发错误的范围内存在的每个变量的数组。

这会导致很多奇怪的行为并阻止引擎中的某些优化,因此在 PHP 7.2 中,鼓励删除此参数的使用。在 PHP 8.0 中,不再传递参数 - 也就是说,PHP 现在只使用 4 个参数调用您的回调。

这个参数一直是“可选的”,因为完全不在签名中列出它是安全的。像这样带有 4 个参数的回调将是 accepted by all versions of PHP:

function my_error_handler($errno, $errstr, $errfile, $errline) {
   // ...
}

正确的解决方案是从您的函数中完全删除该参数,如果:

  • 您正在编写只能在 PHP 8.0 及更高版本上运行的代码;或
  • 您从未在函数中实际使用过该参数

如果实现实际上依赖于该参数,则需要进行其他更改。您可能想要包含带有默认值的参数(使其在 不同 意义上“可选”)并在旧版本的 PHP 上传递时使用它:

function my_error_handler($errno, $errstr, $errfile, $errline, $errcontext=[]) {
   // $errcontext will be populated on older PHP versions, 
   // but will always be an empty array on PHP 8.0 or above
   // Any functionality using it will become useless in future
}

但是,您最好简单地删除依赖它的代码,并找到一个更适合未来的解决方案。

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2017-04-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多