1

In following function we have some arguments with default value, How can I call that function with assigning value to some of them.

function foo($a, $b='def b', $c='def c', $d='def d'){
   //....
}
//call foo for $a='nu a' and $c='nu c'
foo('nu a', $c='nu c'); //but b will be assigned

I want to set value for $c and don't want to assign all of them just for $c.

  1. Not acceptable solution:

    foo('nu a', 'def b', 'nu c');

  2. Not acceptable solution

    //moving c to second argument function foo($a, $c='def c', $b='def b', $d='def d'){ }

So argument is after some default arguments and I don't want to set default value for previous arguments just for one

2
  • is it possible to move all the possible defaults to the right of the function arguments ? Commented Sep 29, 2016 at 14:20
  • 3
    Possible duplicate of PHP Function with Optional Parameters Commented Sep 29, 2016 at 14:21

2 Answers 2

0

Not possible. You're looking for named parameters which is not supported by php.

If you want to do this, you'll have to change your parameter to a single array, and in the function body extract what you need based on the keys.

Other than that, you cannot pass on a value of variable c without passing in b.

Sign up to request clarification or add additional context in comments.

Comments

0

There's no way to "skip" an argument other than to specify a default like false, '' or null.

You will use something like this:

function foo($settings) {
   $a = $settings['a'];
   $b = $settings['b'];
   $c = $settings['c'];
   $d = $settings['d'];
   # code...
}

foo($settings = array(
    'a' => null,
    'b' => 'def b',
    'c' => 'def c',
    'd' => 'def d',
));

Or, in an indexed array, you're able to use list() construct to handle array values, like this :

function foo($settings) {
   list($a, $b, $c, $d) = $settings;
   # code...
}

foo(array(null, 'def b', 'def c', 'def d'));

At the very least you can move whatever you think is not expected most of the time to the end of the argument list in the function definition.

function foo($a, $b = 'def b', $c = 'def c', $d = 'def b') {
   # code...
}
foo($a = 'def a');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.