【问题标题】:PHP: How do I fix this type hinting error?PHP:如何修复这种类型提示错误?
【发布时间】:2021-02-17 17:25:50
【问题描述】:
function foo(int $one, int $two, int &$output): void
{
    $output = $one + $two;
}
foo(1, 2, $result);
var_dump($result);

产生这个错误:

PHP 致命错误:未捕获的 TypeError:传递给 foo() 的参数 3 必须是 int 类型,给定 null

如果不将$result 预先设置为预期类型的​​值等,有什么方法可以避免这种情况?

【问题讨论】:

  • 为什么要为$output 设置类型提示?
  • 首先,我习惯于对所有内容进行完全类型提示,因为我使用了 Psalm 和 PHPStan 等静态分析工具。他们会抱怨缺少类型提示,除非我通过注解/cmets 在异常中编码。

标签: php pass-by-reference type-hinting


【解决方案1】:

来自manual

类型化的传递引用参数

引用参数的声明类型在函数入口时检查,但在函数返回时不检查,所以在函数返回后,参数的类型可能已经改变。

如果您立即为$output 分配一个新值,那么它的类型声明是无关紧要的。要么省略类型声明,要么将其标记为可为空

function foo(int $one, int $two, ?int &$output): void
{
    $output = $one + $two;
}

https://3v4l.org/j91DG


当然,这种类型的模式很复杂,对于像这样简单的事情毫无意义

function foo(int $one, int $two): int
{
    return $one + $two;
}

【讨论】:

  • 我的真实代码要复杂得多,实际上通过引用参数返回而不是返回值是有意义的。 ;-)
  • 个人意见,但我觉得通过引用/输出参数返回很少合适
  • 我同意。管理扩展我正在使用的库是一种丑陋的工作。
【解决方案2】:

您可以在 PHP 8 中使用联合类型:

function foo(int $one, int $two, int|null &$output): void
{
    $output = $one + $two;
}
foo(1, 2, $result);
var_dump($result);

【讨论】:

  • 如果你与null联合,使用?int不是更有意义
  • @Phil,同样的东西不同的味道 imo
猜你喜欢
  • 2022-08-06
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 2016-09-28
  • 1970-01-01
  • 2018-07-27
相关资源
最近更新 更多