Is it possible in php
like in python
to have named function parameters? An example use case is:
function foo($username = "", $password = "", $timeout = 10) {
}
I want to override $timeout
:
foo("", "", 3);
Ugly. I would much rather do:
foo(timeout=3);
PHP 8.0 added support for named arguments with the acceptance of an RFC.
Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed.
E.g. to pass just the 3rd optional parameter in your example:
foo(timeout: 3);
Prior to PHP 8 named parameters were not possible in PHP. Technically when you call foo($timeout=3)
it is evaluating $timeout=3
first, with a result of 3
and passing that as the first parameter to foo()
. And PHP enforces parameter order, so the comparable call would need to be foo("", "", $timeout=3)
. You have two other options:
func_get_args()
or use the ...
variable length arguments feature in PHP 5.6+. Based on the number of parameters you can then decide how to treat each. A lot of JQuery functions do something like this. This is easy but can be confusing for those calling your functions because it's also not self-documenting. And your arguments are still not named.