有没有一种干净的方法可以在PHP中使用未定义的变量作为可选参数



有什么好的方法可以使用(可能(未定义的变量(如来自外部输入(作为可选的Function参数吗?

<?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

但是使用这个,我仍然需要检查两次参数:一次是在调用函数之前设置的,一次是函数内部为null。

还有其他好的解决方案吗?

在这种情况下,理想情况下不会通过$b。我不记得遇到过这样的情况:我不知道变量是否存在,并将其传递给函数:

foo($a);

但要做到这一点,您需要确定如何调用函数:

isset($b) ? foo($a, $b) : foo($a);

这有点像黑客,但如果你无论如何都需要一个参考,它就会被创建:

function foo($a, &$b){
$b = $b ?? 4;
var_dump($b);
}
$a = 1;
foo($a, $b);

如果这确实是一个需求,我会这样做。只是用提供的值的总和进行测试,只是为了展示一个示例。

<?php
$x = 1;
//Would generate notices but no error about $y and t    
//Therefore I'm using @ to suppress these
@$sum = foo($x,$y,4,3,t);  
echo 'Sum = ' . $sum;
function foo(... $arr) {
return array_sum($arr);
}

将输出。。。

Sum = 8

基于给定的数组(带…$arr的未知参数数量(

array (size=5)
0 => int 1
1 => null
2 => int 4
3 => int 3
4 => string 't' (length=1)

array_sum()仅将1,4和3相加,此处=8。


即使以上确实有效,我也不建议使用,因为无论什么数据都可以发送到您的函数foo(),而无需您对其进行任何控制。当涉及到任何类型的用户输入时,在使用用户的实际数据之前,您应该在代码中尽可能多地进行验证。

最新更新