Does PHP Have "Named Parameters" So That Early Arguments Can Be Omitted and Later Arguments Can Be Written

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.

can php function parameters be passed in different order as defined in declaration

Absolutely not.

One way you'd be able to pass in unordered arguments is to take in an associative array:

function F($params) {
if(!is_array($params)) return false;
//do something with $params['A'], etc...
}

You could then invoke it like this:

F(array('C' => 3, 'A' => 1, 'B' => 1));

PHP : Passing 2nd argument on function but retain the default value of first argument

No you can't do that in this way. PHP excpects the values in the order you defined in the function.
However it is possible to pass data to your function as an array.

$res = check(array('a' => $defaulta, ..., 'c' => 5))

Where you have your default values in somethin like $defaulta/b/c. Or just write them hardcoded.

Hope this helps!

Is it possible to omit random parameters in a function call?

PHP doesn't have named parameters (or keyword arguments). I recommend you try the following style:

public function table_creator($thread, $table_body, $options=array()){
$default_options = array(
"class" => "datagrid",
// you can add more default options here
);
$options = array_merge($default_options, $options);
// some code
}

Then you can call it like this:

echo SomeClass::table_creator($this->report_keys, $report,
array("caption" => "Answers");

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);
}
}

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.

Is it a bad idea to name parameters like this in PHP?

I think this is a bad idea from the perspective that you don't have any safety if you get the order wrong. Using a map is a much safer way of emulating this. You also have the side effect of setting the values of these variables in the local scope, which may or may not be an issue.

calculateArea( $height = 5, $width = 10 ); # oops!

function calculateArea( $width, $height ) {
// do calculations here...
}

With a array (map), it doesn't matter what order you put them in.

calculateArea( array( 'height' => 5, 'width' => 10 ) ) # yea!

function calculateArea( $dimensions ) {
$width = $dimensions['width'];
$height = $dimensions['height'];
}


Related Topics



Leave a reply



Submit