Reputation: 1061
Let's define this function:
function fooFunction($a, $b='foo', $c){}
If I call it like:
$foo = fooFunction("bar", "buzz");
...will 'buzz' be asigned to $c or to $b?
Upvotes: 0
Views: 523
Reputation: 522636
The presence or absence of default values for a parameter does not in any way influence what arguments will be assigned to what parameters; the first passed argument always goes to the first parameter, the second to the second and so on. If no value was passed for a parameter and it has a default value, its default value is used instead.
In PHP <7.1, not supplying an argument for parameters without default value merely produced a warning. The parameter would then be undefined inside the function:
function fooFunction($a, $b='foo', $c) {
var_dump($c);
}
$foo = fooFunction("bar", "buzz");
Warning: Missing argument 3 for fooFunction()
Notice: Undefined variable: c
NULL
Since PHP 7.1 it finally acts sane and throws an exception:
Fatal error: Uncaught ArgumentCountError:
Too few arguments to function fooFunction(),
2 passed and exactly 3 expected
Stack trace:
#0 fooFunction('bar', 'buzz')
It's still insane that you can define parameters without default value after parameters with, since in practice that makes little sense; perhaps PHP is counting on you not to do that precisely because there's no practical purpose.
Upvotes: 1