6

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?

3
  • Your problem is the function call! You can't set the default argument with "dynamic" data Commented Apr 7, 2015 at 14:26
  • Yes ^ But good thinking Commented Apr 7, 2015 at 14:27
  • I would use dependency injection. Pass in an object of type apiKeyConfig or something like that, where an apiKeyConfig requires the parameters you mention, and then typehint that the argument must be an instance of apiKeyConfig. Commented Apr 7, 2015 at 14:53

3 Answers 3

5

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',
        ];    
    }
    //...
}
Sign up to request clarification or add additional context in comments.

7 Comments

Would you recommend this over the other solution in this question?
@kmgilbert100 Well in both answers you have to make sure that the placeholders are unique. The advantage I see here is that you can use the placeholder multiple times and you don't need an if statement for every placeholder. (Just added another example which I think may be the best solution, since if you would pass an empty array you don't have to check for that)
seems like even a better solution, I like it thanks!
just thinking actually though the second option would not work, because what if I wanted to only pass user-id through and not level and ignore-limits wouldnt only passing one through get rid of the default level and ignore-limit values?
@kmgilbert100 So you mean if you pass an array with like 2 elements, that it wouldn't choose the default array?
|
1

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()
    }
    ...
}

1 Comment

Ic, I need this function to be within the default values, would it be best to just do an array merge within the function and set $data to null by default?
0

More universal solution with array_mearge. This way you can rewrite any parameter without having to check each of them individually.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.