0

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

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

但是使用它我仍然必须检查参数两次:一次如果在调用函数之前设置,一次如果它在函数内部为空。

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

4

2 回答 2

2

理想情况下,您不会$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);
于 2020-05-06T21:23:07.623 回答
-1

如果这实际上是一个要求,我会做这样的事情。仅使用提供的值的总和进行测试以显示示例。

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

...基于给定的数组(未知 nr 个参数,... $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()而您无法控制它。当涉及到任何类型的用户输入时,在使用来自用户的实际数据之前,您应该始终在代码中尽可能多地进行验证。

于 2020-05-06T21:51:13.163 回答