我建议按如下方式更改函数声明,以便您可以执行所需的操作:
function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}
if (null === $y) {
$y = "some other value";
}
code here!
}
这样,您可以进行类似调用并使其按所需方式工作,其中第二个参数仍获取其默认值。foo('blah', null, 'non-default y value');
$x
使用此方法时,传递 null 值意味着当您想要覆盖某个参数后面的参数的默认值时,需要该参数的默认值。
如其他答复所述,
默认参数仅用作函数的最后一个参数。如果要在函数定义中声明默认值,则无法省略一个参数并覆盖其后面的一个参数。
如果我有一个可以接受不同数量的参数和不同类型的参数的方法,我经常声明类似于Ryan P显示的答案的函数。
这是另一个例子(这没有回答你的问题,但希望能提供信息:
public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();
// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}