PHP: 如何修复此类型提示错误?

PHP: How do I fix this type hinting error?

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

产生此错误:

PHP Fatal error: Uncaught TypeError: Argument 3 passed to foo() must be of the type int, null given

有没有办法在不预先设置 $result 为预期类型等值的情况下避免这种情况?

来自manual

Typed pass-by-reference Parameters

Declared types of reference parameters are checked on function entry, but not when the function returns, so after the function had returned, the argument's type may have changed.

假设您立即为 $output 分配一个新值,它的类型声明是无关紧要的。省略类型声明或将其标记为 nullable

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;
}

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

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