PHP函数数组默认值?

我有一个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',
        ];    
    }
    //...
}

转载注明原文:PHP函数数组默认值? - 代码日志