Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Default Function Parameter values, how to 'pass default value' for 'not last' parameters?

Most of us know the following syntax:

function funcName($param='value'){     echo $param; } funcName();  Result: "value" 

We were wondering how to pass default values for the 'not last' paramater? I know this terminology is way off, but a simple example would be:

function funcName($param1='value1',$param2='value2'){     echo $param1."\n";     echo $param2."\n"; } 

How do we accomplsh the following:

funcName(---default value of param1---,'non default'); 

Result:

value1 not default 

Hope this makes sense, we want to basically assume default values for the paramaters which are not last.

Thanks.

like image 622
anonymous-one Avatar asked May 15 '12 08:05

anonymous-one


People also ask

Do default parameters have to be last?

Rule Details. This rule enforces default parameters to be the last of parameters.

Can you assign the default values to a function parameters in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

Can we add two default values in function in PHP?

As stated in other answers, default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


1 Answers

PHP doesn't support what you're trying to do. The usual solution to this problem is to pass an array of arguments:

function funcName($params = array()) {     $defaults = array( // the defaults will be overidden if set in $params         'value1' => '1',         'value2' => '2',     );      $params = array_merge($defaults, $params);      echo $params['value1'] . ', ' . $params['value2']; } 

Example Usage:

funcName(array('value1' => 'one'));                    // outputs: one, 2 funcName(array('value2' => 'two'));                    // outputs: 1, two funcName(array('value1' => '1st', 'value2' => '2nd')); // outputs: 1st, 2nd funcName();                                            // outputs: 1, 2 

Using this, all arguments are optional. By passing an array of arguments, anything that is in the array will override the defaults. This is possible through the use of array_merge() which merges two arrays, overriding the first array with any duplicate elements in the second array.

like image 105
MrCode Avatar answered Sep 23 '22 11:09

MrCode