超全局变量作为 php 函数中的参数

Superglobals as parameters in php functions

我发现自己需要为超全局的某些方法参数设置默认值,例如:

public function some_function ($foo = $_POST['foo'], $bar = $_POST['bar']){
    //some action
}

这让我很生气

Parse error: syntax error, unexpected '$_POST' (T_VARIABLE) in /script.php on line (the number of line matches method definition)

如果它喜欢:

public function some_function ($foo = "{$_POST['foo']}", $bar = "{$_POST['bar']}")

解析器抛出:

Parse error: syntax error, unexpected '"' 

有没有办法从 PHP superglobals 设置默认方法参数值?

参数默认值必须是常量表达式,所以你可以这样做:

public function some_function ($foo = null, $bar = null)
{
    if ($foo === null) {
        $foo = $_POST['foo'];
    }
    if ($bar === null) {
        $bar = $_POST['bar'];
    }
}

如果你想花哨,你可以确保你的默认值有默认值:

public function some_function ($foo = null, $bar = null)
{
    if ($foo === null) {
        $foo = $_POST['foo'] ?? 'default foo';
    }
    if ($bar === null) {
        $bar = $_POST['bar'] ?? 'default bar';
    }
}