Does PHP Allow Named Parameters So That Optional Arguments Can Be Omitted from Function Calls

Does PHP allow named parameters so that optional arguments can be omitted from function calls?

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.

A "solution" would be to use only one parameter, an array, and always pass it... But don't always define everything in it.

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 :

  • You will lose the phpdoc
  • Your IDE will not be able to provide any hint anymore... Which is bad

So I'd go with this only in very specific cases -- for functions with lots of optional parameters, for instance...

Is it possible to use named function parameters in PHP?

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:

  • Have your function take an array as parameter and check the array keys. I personally find this ugly but it works and is readable. Upside is simplicity and it's easy to add new parameters later. Downside is your function is less self-documenting and you won't get much help from IDEs (autocomplete, quick function param lookups, etc.).
  • Set up the function with no parameters and ask PHP for the arguments using 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.

Is it possible to skip parameters that have default values in a function call?

Found this, which is probably still correct:

http://www.webmasterworld.com/php/3758313.htm

Short answer: no.

Long answer: yes, in various kludgey ways that are outlined in the above.

Optional parameters in PHP function without considering order

This is modified from one of the answers and allows arguments to be added in any order using associative arrays for the optional arguments

 function createUrl($host, $path, $argument = []){
$optionalArgs = [
'protocol'=>'http',
'port'=>80];
if( !is_array ($argument) ) return false;
$argument = array_intersect_key($argument,$optionalArgs);
$optionalArgs = array_merge($optionalArgs,$argument);
extract($optionalArgs);
return $protocol.'://'.$host.':'.$port.'/'.$path;
}



//No arguments with function call
echo createUrl ("www.example.com",'no-arguments');
// returns http://www.example.com:80/no-arguments

$argList=['port'=>9000];
//using port argument only
echo createUrl ("www.example.com",'one-args', $argList);
//returns http://www.example.com:9000/one-args

//Use of both parameters as arguments. Order does not matter
$argList2 = ['port'=>8080,'protocol'=>'ftp'];
echo createUrl ("www.example.com",'two-args-no-order', $argList2);
//returns ftp://www.example.com:8080/two-args-no-order

Any way to specify optional parameter values in PHP?

PHP does not support named parameters for functions per se. However, there are some ways to get around this:

  1. Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
  2. If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
  3. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
  4. If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed.

Function call missing argument

You have a few options to handle this case. Here the 2 I can think about.

Using an array

With an array you don't bother with how many arguments your function receives, and each argument is named (with the key in the array)

function fu($param = array()) {
// you can test here is $param['arg1'] exists, $param['arg2'] and so on
echo 'helo world';
}

Using func_get_args

This way you can how many arguments you like to the function, but they aren't named

function fu()
{
foreach (func_get_args() as $index => $value) {
echo "Argument {$index} is: \n", var_export($value);
}
}


Related Topics



Leave a reply



Submit