我有一个 PHP 函数,里面有一个数组。我把数组放在里面,所以参数是可选的,这些是默认值。示例
/**
* Creates New API Key
*
* @return Response
*/
public function create(
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
]){
...
}
但是我一直报错
syntax error, unexpected '(', expecting ']'
所以我假设你在构造函数时不能传递这样的数组。执行此操作或修复的更好方法是什么?
函数参数的默认值只能使用标量类型。
您还可以在手册中阅读:http://php.net/manual/en/functions.arguments.php#functions.arguments.default
引自那里:
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
编辑:
但是如果你仍然需要这个值作为数组中的默认值,你可以这样做:
只需使用一个占位符,如果使用默认数组,您可以将其替换为 str_replace()
。如果您多次需要默认数组中函数的返回值,这也有好处,您只需要使用相同的占位符,两者都将被替换。
public function create(
$data = [
"user-id" => "::PLACEHOLDER1::",
//^^^^^^^^^^^^^^^^ See here just use a placeholder
"level" => '1',
"ignore-limits" => '0',
]){
$data = str_replace("::PLACEHOLDER1::", Auth::id(), $data);
//^^^^^^^^^^^ If you didn't passed an argument and the default array with the placeholder is used it get's replaced
//$data = str_replace("::PLACEHOLDER2::", Auth::id(), $data); <- AS many placeholder as you need; Just make sure they are unique
//...
}
你可以做的另一个想法是设置一个默认数组,你可以检查它然后像这样分配真正的数组:
public function create($data = []){
if(count($data) == 0) {
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
];
}
//...
}