kev*_*100 5 php arrays function
我有一个PHP函数,里面有一个数组.我把数组放在里面,所以参数将是选项,这些将是默认值.例
/**
* Creates New API Key
*
* @return Response
*/
public function create(
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
]){
...
}
Run Code Online (Sandbox Code Playgroud)
但是我一直在收到错误
语法错误,意外'(',期待']'
所以我假设在构造函数时你不能传递这样的数组.什么是更好的方法来做到这一点或修复?
您只能使用标量类型作为函数参数的默认值.
您也可以在手册中阅读:http://php.net/manual/en/functions.arguments.php#functions.arguments.default
从那里引用:
的缺省值必须是常量表达式,而不是(例如)一个变量,类成员,或者一个函数调用.
编辑:
但是如果您仍然需要将此值作为数组中的默认值,则可以执行以下操作:
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
//...
}
Run Code Online (Sandbox Code Playgroud)
您可以做的另一个想法是设置一个默认数组,您可以检查,然后像这样分配真实数组:
public function create($data = []){
if(count($data) == 0) {
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
];
}
//...
}
Run Code Online (Sandbox Code Playgroud)