Any Way to Specify Optional Parameter Values in PHP

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.

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

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

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
}

PHP optional parameter

That's because the $param = 'value' bit in the function declaration is not executed every time the function is called.

It only comes into play if you don't pass a value for that parameter.

Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.

if true === $param holds no value
$param = 'value'
endif

In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.

Edit: Note that the snippet above is deliberately just pseudo code as it's tricky to accurately express what's going using PHP on once PHP has been compiled. See the comments for more info.

PHP - Make reference parameter optional?

Taken from PHP official manual:

NULL can be used as default value, but it can not be passed from outside

<?php

function foo(&$a = NULL) {
if ($a === NULL) {
echo "NULL\n";
} else {
echo "$a\n";
}
}

foo(); // "NULL"

foo($uninitialized_var); // "NULL"

$var = "hello world";
foo($var); // "hello world"

foo(5); // Produces an error

foo(NULL); // Produces an error

?>

Optional parameters in php

The first argument is always passed to the first variable in the parameters, the second to the second and so on, regardless of whether they are optional or not.

The only difference between an optional and a non-optional parameter is that a warning is thrown when there are not enough arguments in the call to fulfill all non-optional parameters.

function f($a = 1, $b, $c, $d = 2)
{
var_dump($a, $b, $c, $d);
}
f('x');

Inside the function $a will be "x", $b and $c will be null and $d will be 2 but a warning will be thrown.

Therefore it makes no sense to have optional parameters left of non-optional ones - although that would be syntactically correct - because you could never leave them out in the call without generation a warning.



Related Topics



Leave a reply



Submit