PHP函数数组默认值


PHP Function Array Default Values?

我有一个PHP函数,里面有一个数组。我把数组放在里面,所以参数是可选的,这些将是默认值。示例

/**
 * Creates New API Key
 *
 * @return Response
 */
public function create(
    $data = [
        "user-id" => Auth::id(),
        "level" => '1',
        "ignore-limits" => '0',
    ]){
    ...
}

然而,我不断得到错误

语法错误,意外的"(",应为"]"

所以我假设在构造函数时不能传递这样的数组。什么是更好的方法或解决方案?

函数参数的默认值只能使用标量类型。

您也可以在手册中阅读: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
    //...
}

你可以做的另一个想法是设置一个默认数组,你可以检查它,然后像这样分配真正的数组:

public function create($data = []){
    if(count($data) == 0) {
        $data = [
            "user-id" => Auth::id(),
            "level" => '1',
            "ignore-limits" => '0',
        ];    
    }
    //...
}

这里的问题是:

Auth::id()

这调用了一个方法,在这种情况下这样做是非法的

我会这样解决:

public function create(
    $data = [
        "user-id" => -1,
        "level" => '1',
        "ignore-limits" => '0',
    ]){
    if($data['user-id'] === -1) {
        $data['user-id'] = Auth::id()
    }
    ...
}

更通用的array_mearge解决方案。通过这种方式,您可以重写任何参数,而不必单独检查每个参数。

function create($somthing, $settings = [])
{
    $default = [
        'date' => date("Y-m-d H:i:s"),
        'bold' => false,
        'italic' => false,
    ];
    $settings = array_merge($default, $settings);
    ...
}