我发现自己需要为来自超全局的一些方法参数设置一个默认值,例如:
public function some_function ($foo = $_POST['foo'], $bar = $_POST['bar']){
//some action
}这把我扔了
解析错误:语法错误,意外的'$_POST‘(T_VARIABLE)在线/script.php (行数匹配方法定义)
如果它喜欢:
public function some_function ($foo = "{$_POST['foo']}", $bar = "{$_POST['bar']}")解析器抛出:
Parse error: syntax error, unexpected '"' 是否有方法从PHP超级全局设置默认方法参数值?
发布于 2018-02-20 16:41:03
参数默认值必须是常量表达式,因此您可以这样做:
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';
}
}https://stackoverflow.com/questions/48889998
复制相似问题