【问题标题】:Is there a clean way to use undefined variables as optional parameters in PHP?有没有一种干净的方法可以在 PHP 中使用未定义的变量作为可选参数?
【发布时间】:2020-05-06 21:12:11
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: php error-handling undefined-variable


    【解决方案1】:

    理想情况下,您不会在这种情况下通过 $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);
    

    【讨论】:

    • 我也考虑过这个选项。它确实有效,但仍然感觉有些不对劲。我想没有更好的选择。
    【解决方案2】:

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

    <?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-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多