9

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?

Alex S
  • 25,241
  • 18
  • 52
  • 63

5 Answers5

12

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.

Sasha Chedygov
  • 127,549
  • 26
  • 102
  • 115
  • +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 Jul 12 '09 at 01:56
  • 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. – Sasha Chedygov Jul 12 '09 at 02:04
  • 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. – Alex S Jul 12 '09 at 02:10
  • 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. – Sasha Chedygov Jul 12 '09 at 02:21
  • I use Syntactic and it's awesome https://github.com/topclaudy/php-syntactic – cjdaniel Jun 19 '16 at 18:35
4

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
  • 480,997
  • 81
  • 517
  • 436
3

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

beppe9000
  • 1,056
  • 1
  • 13
  • 28
Michael Haren
  • 105,752
  • 40
  • 168
  • 205
0

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

Tiberiu
  • 2,870
  • 3
  • 20
  • 17
0

What if you put all your parameters into an argument object and then parse that?

function abc(arguments) {
  foreach (index=>value in arguments) { ... }
}
abc({message: "Out of condoms.", haveSex: false, code: 404});
rxgx
  • 5,089
  • 2
  • 35
  • 43