Is it possible in PHP to specify a named optional parameter when calling a function/method, skipping the ones you don't want to specify (like in python)?
Something like:
function foo($a, $b = '', $c = '') { // whatever } foo("hello", $c="bar"); // we want $b as the default, but specify $c
When creating functions in PHP it is possible to provide default parameters so that when a parameter is not passed to the function it is still available within the function with a pre-defined value. These default values can also be called optional parameters because they don't need to be passed to the function.
By default, all parameters of a method are required. But in C# 4.0, the concept of optional parameters was introduced that allows developers to declare parameters as optional.
Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
No, it is not possible (before PHP 8.0): if you want to pass the third parameter, you have to pass the second one. And named parameters are not possible either.
For instance :
function foo($params) { var_dump($params); }
And calling it this way : (Key / value array)
foo([ 'a' => 'hello', ]); foo([ 'a' => 'hello', 'c' => 'glop', ]); foo([ 'a' => 'hello', 'test' => 'another one', ]);
Will get you this output :
array 'a' => string 'hello' (length=5) array 'a' => string 'hello' (length=5) 'c' => string 'glop' (length=4) array 'a' => string 'hello' (length=5) 'test' => string 'another one' (length=11)
But I don't really like this solution :
So I'd go with this only in very specific cases -- for functions with lots of optional parameters, for instance...
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