Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function Array Default Values? [duplicate]

I have a PHP function with a array within. I put the array inside so the parameters would be option and these would be the defaults. Example

/**
 * Creates New API Key
 *
 * @return Response
 */

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

However I keep getting the error

syntax error, unexpected '(', expecting ']'

So I assume that you cant pass a array like this when constructing a function. What would be a better way to do this or a fix?

like image 812
kevingilbert100 Avatar asked Apr 07 '15 14:04

kevingilbert100


2 Answers

You can only use scalar types for the default values of function arguments.

You can also read this in the manual: http://php.net/manual/en/functions.arguments.php#functions.arguments.default

And a quote from there:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

EDIT:

But if you still need this value as default value in the array you could do something like this:

Just use a placeholder which you can replace with str_replace() if the default array is used. This also has the advantage if you need the return value of the function in the default array multiple times you just need to use the same placeholder and both are going to be replaced.

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
    //...
}

Another idea you could do is set a default array which you can check and then assign the real array like this:

public function create($data = []){
    if(count($data) == 0) {
        $data = [
            "user-id" => Auth::id(),
            "level" => '1',
            "ignore-limits" => '0',
        ];    
    }
    //...
}
like image 126
Rizier123 Avatar answered Sep 19 '22 05:09

Rizier123


The issue here is the:

Auth::id()

This calls a method which is illegal to do in this context

I would solve it like this:

public function create(
    $data = [
        "user-id" => -1,
        "level" => '1',
        "ignore-limits" => '0',
    ]){
    if($data['user-id'] === -1) {
        $data['user-id'] = Auth::id()
    }
    ...
}
like image 24
CodeTower Avatar answered Sep 20 '22 05:09

CodeTower