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

Hamid
  • 11
  • 1
  • is it possible to move all the possible defaults to the right of the function arguments ? – atoms Sep 29 '16 at 14:20
  • 3
    Possible duplicate of [PHP Function with Optional Parameters](http://stackoverflow.com/questions/3978929/php-function-with-optional-parameters) – Rax Weber Sep 29 '16 at 14:21

2 Answers2

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.

M.Alnashmi
  • 582
  • 1
  • 4
  • 15
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');
Anass
  • 59
  • 2
  • 8