可能这是 PHP 的限制,但是否有可能以某种方式调用函数 - 并强制执行可选参数的“默认”值 - 即使在函数调用中,给出了可选参数(并且 == null
)?
也许更容易表达我的意思:
<?php
function funcWithOptParam($param1, $param2 = 'optional') {
print_r('param2: ' . $param2);
}
funcWithOptParam('something'); // this is the behaviour I want to reproduce
// this will result in 'param2: optional'
funcWithOptParam('something', null); // i want $param2 to be 'optional', not null
// this will result in 'param2: ' instead of 'param2: optional'
?>
现在,最简单的答案是“然后不要写 null
”——但在我的特殊情况下,我得到一个参数 array
用于 function
调用,并且只能这样做:
<?php
funcWithOptParam($param[0], $param[1]);
?>
所以即使$param[1]
是null
,null
也会覆盖可选参数的默认值
我只看到一个解决方案——跳过可选参数,然后这样做:
<?php
function funcWithOptParam($something, $notOptional) {
if($notOptional === null) {
$notOptional = 'defaultvalue';
}
...
}
?>
但我想知道是否有其他解决方案。 PHP 中是否存在“真实的”null
值?这真的转化为“无”?像 js 中的 undefined
之类的东西?
最佳答案
为什么不将整个数组作为函数参数传递? 您只需这样调用它:
funcWithOptParams($params);
然后这样处理:
function funcWithOptParams($params) {
if(!isset($params[1])) {
$params[1] = 'defaultvalue';
}
...
}
这种方法使您可以只传递您想要指定的参数,并在您不想指定的参数中使用默认值。作为奖励,您不必担心参数的顺序。
关于php - 如何获取可选参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13208257/