How to skip arguments when their default is desired

Associative arrays aren't so bad here, especially when the argument list starts getting bigger:

function abc($args = array()) {
    $defaults = array('c' => 'foo', 'd' => 'bar');
    $args = array_merge($defaults, $args);
}

If you wanted to explicitly make some of them required, you could put them in front:

function abc($a, $b, $args = array()) {

}

It's up to you, I've seen big projects use both approaches (forcing passing null and this) and I honestly sort of prefer this one. If you are familiar with Javascript a lot of scripts take use of this behavior when you pass options to them, so it's not completely foreign.


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.


PHP doesn't support this. (non-explicit ref)

Tags:

Php