tags:

views:

369

answers:

5

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');
+2  A: 

Found this, which is probably still correct:

http://www.webmasterworld.com/php/3758313.htm

Short answer: no.

Long answer: yes, in various kludgey ways that are outlined in the above.

sprugman
+1  A: 

You pretty much found the answer, but the academic/high-level approach is function currying which I honestly never found much of a use for, but is useful to know exists.

Tom Ritter
I don't think currying can do anything about default argument values - they are pretty much mutually exclusive concepts.
jpalecek
+2  A: 

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

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

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

  // now, do stuff!
}

foo(
  array(
    'another_argument' => 'not the default value!',
  )
);
ceejayoz
+3  A: 

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"
Gumbo