Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to skip parameters that have default values in a function call? [duplicate]

I have this:

function foo($a='apple', $b='brown', $c='Capulet') {
    // do something
}

Is something like this possible:

foo('aardvark', <use the default, please>, 'Montague');
like image 432
sprugman Avatar asked Feb 23 '09 21:02

sprugman


2 Answers

If it’s your function, you could use null as wildcard and set the default value later inside the function:

function foo($a=null, $b=null, $c=null) {
    if (is_null($a)) {
        $a = 'apple';
    }
    if (is_null($b)) {
        $b = 'brown';
    }
    if (is_null($c)) {
        $c = 'Capulet';
    }
    echo "$a, $b, $c";
}

Then you can skip them by using null:

foo('aardvark', null, 'Montague');
// output: "aarkvark, brown, Montague"
like image 149
Gumbo Avatar answered Nov 07 '22 07:11

Gumbo


If it's your own function instead of one of PHP's core, you could do:

function foo($arguments = []) {
  $defaults = [
    'an_argument' => 'a value',
    'another_argument' => 'another value',
    'third_argument' => 'yet another value!',
  ];

  $arguments = array_merge($defaults, $arguments);

  // now, do stuff!
}

foo(['another_argument' => 'not the default value!']);
like image 39
ceejayoz Avatar answered Nov 07 '22 05:11

ceejayoz