Php – How to skip arguments when their default is desired


If I have a function like this:

function abc($a,$b,$c = 'foo',$d = 'bar') { ... }

And I want $c to assume it's default value, but need to set $d, how would I go about making that call in PHP?

Best Solution

PHP can't do this, unfortunately. You could work around this by checking for null. For example:

function abc($a, $b, $c = 'foo', $d = 'bar') {
    if ($c === null)
        $c = 'foo';
    // Do something...

Then you'd call the function like this:

abc('a', 'b', null, 'd');

No, it's not exactly pretty, but it does the job. If you're feeling really adventurous, you could pass in an associative array instead of the last two arguments, but I think that's way more work than you want it to be.