有没有什么好方法可以使用(可能)未定义的变量(如来自外部输入)作为可选的函数参数?
<?php
$a = 1;
function foo($a, $b=2){
//do stuff
echo $a, $b;
}
foo($a, $b); //notice $b is undefined, optional value does not get used.
//output: 1
//this is even worse as other erros are also suppressed
@foo($a, $b); //output: 1
//this also does not work since $b is now explicitly declared as "null" and therefore the default value does not get used
$b ??= null;
foo($a,$b); //output: 1
//very,very ugly hack, but working:
$r = new ReflectionFunction('foo');
$b = $r->getParameters()[1]->getDefaultValue(); //still would have to check if $b is already set
foo($a,$b); //output: 12
到目前为止,我能想到的唯一半有用的方法是不将默认值定义为参数,而是在实际函数内部,并使用“null”作为中介,如下所示:
<?php
function bar ($c, $d=null){
$d ??= 4;
echo $c,$d;
}
$c = 3
$d ??= null;
bar($c,$d); //output: 34
但是使用它我仍然必须检查参数两次:一次如果在调用函数之前设置,一次如果它在函数内部为空。
还有其他好的解决方案吗?