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?
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?
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.
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 doesn't support this. (non-explicit ref)
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});