tags:

views:

116

answers:

4

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?

+2  A: 

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

Michael Haren
A: 

hi there,

I don't believe that you can do this in php.

Tiberiu Hajas
+7  A: 

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.

musicfreak
+1 Nice work around. I'd probably leave out the $='foo' part in the signature since the null check handles the default now.
Michael Haren
True, but what if you want to omit both `$c` and `$d`? It would now throw an error because the function has 3 required arguments.
musicfreak
The problem is that my functions have 5+ vars. This is for a system for possible future people who aren't PHP savvy to manipulate the code by setting specific variables.
Shadow
Like I said, there's no other way to do this. You could, like I mentioned, pass an associative array into the function and just set any unset values to their defaults. But otherwise, you're out of luck; sorry.
musicfreak
+2  A: 

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.

Paolo Bergantino