Old question, but here is some more information.
As stated in the other answers, PHP does not directly support named parameters. VBA is another language which has that luxury.
In PHP, you can use a fairly reasonable substitute. PHP’s array handling is particularly good, and you can use an associative array to pass an array of parameters, as follows:
function foo($parms=[]) {
$username = $parms['username'] ?? '…';
$password = $parms['password'] ?? '…';
$timeout = $parms['timeout'] ?? '…';
}
foo(['timeout'=>10]);
Note the use of the ??
operator to allow a simple default if the input array element doesn’t exist. Before PHP 7, you would use ?:
which is subtly different, but gives the same result in this case. Thanks to @LeeGee for picking this up.
Not as slick, but named parameters have another important role: they allow you to work with a large number of options without an excessively long list of ordered parameters.
An alternative way of writing the function is to use the `extract function:
function foo($parms=[]) {
$username = '…';
$password = '…';
$timeout = '…';
extract($parms,EXTR_IF_EXISTS);
}
Here the extract
function copies the values into the variables, but only if they have already been defined. This prevents importing variables you didn’t know about.