传递默认值而不是引用

Pass default value instead of reference

我有这样的功能(使用 PHP 7.1):

function myfunction(&$first = null, $second = null)
{   // do something
}

我想实现的是第一个参数传null,第二个参数传something:

myfunction(null, $something);

当我这样做时,出现“只有变量可以通过引用传递”错误。

当然,null 是第一个参数的默认值,因此该函数被设计为将 null 作为第一个参数处理。

有办法吗?

您可以发送一个未声明的变量,而不是发送 null,例如 (DEMO):

<?php
function myfunction(&$first = null, $second = null)
{   // do something
}
myfunction($null, $something);

这将有助于执行函数而不破坏您的代码。

PHP 8+:

在 PHP 8 中我们有 Named Parameters, so we don't even need to pass the $first param if we don't want to (DEMO):

<?php
function myfunction(&$first = null, $second = null)
{   // do something
}
myfunction(second: $something);

不可能。如果函数有多个参数,引用不能为空作为第一个参数。

这里有一些可能性:

function func($a = null, &$b = null) {}
function funcb(&$a, $b = null) {}

呼叫:

$a = null;
func($a, $b)
funcb($a)