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

有没有一种干净的方法可以将未定义的变量用作PHP中的可选参数?,php,error-handling,undefined-variable,Php,Error Handling,Undefined Variable,有没有什么好方法可以使用(潜在的)未定义的变量(比如来自外部输入的变量)作为可选的函数参数 <?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 a

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

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

理想情况下,在这种情况下,您不会通过
$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);
}
…基于给定的数组(未知的参数数量,带有…$arr)

array_sum()
此处仅对1,4和3求和=8



即使上面的方法确实有效,我也不推荐它,因为这样无论什么数据都可以发送到你的函数
foo()
,而你对它没有任何控制权。当涉及到任何类型的用户输入时,在使用来自用户的实际数据之前,您应该始终在代码中尽可能多地验证

我也考虑过这个选择。它确实有效,但仍然感觉有点不对劲。我想没有更好的选择了。
<?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
array (size=5)
  0 => int 1
  1 => null
  2 => int 4
  3 => int 3
  4 => string 't' (length=1)