PHP Optional Parameters - Specify Parameter Value by Name

PHP Optional Parameters - specify parameter value by name?

No, in PHP that is not possible as of writing. Use array arguments:

function doSomething($arguments = array()) {
// set defaults
$arguments = array_merge(array(
"argument" => "default value",
), $arguments);

var_dump($arguments);
}

Example usage:

doSomething(); // with all defaults, or:
doSomething(array("argument" => "other value"));

When changing an existing method:

//function doSomething($bar, $baz) {
function doSomething($bar, $baz, $arguments = array()) {
// $bar and $baz remain in place, old code works
}

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.

PHP Function with Optional Parameters

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

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...

How to only pass an optional parameter to a PHP function by keeping all other mandatory/optional parameters(if any) equal to their default values?

Passing '' does not mean falling back to default argument value. It means just that — trying to pass an empty string.

You would need to reproduce defaults if you want to achieve this:

htmlspecialchars('&', ENT_COMPAT | ENT_HTML401, ini_get('default_charset'), FALSE);

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

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}

Passing an optional parameter in PHP Function

try this:

function test($required, $optional = NULL){..} 

then you can call

test($required, $optional)

and with $optional null

test($required);  


Related Topics



Leave a reply



Submit