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?
It's not possible to skip it, but you can pass the default argument using ReflectionFunction .
You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.
Default arguments can be skipped from function call.
During a function call, only giving mandatory argument as a keyword argument. Optional default arguments are skipped.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With