PHP Default Function Parameter Values, how to "pass the default value" to "not the last" parameters?

Most of us know the following syntax:

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

We were wondering how to pass the default values ​​for the "not the last" parameter? I know this terminology is gone, but a simple example:

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

How do we do 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 parameters that are not the last.

Thank.

+42
function php parameters default
May 15 '12 at 8:44
source share
3 answers

PHP does not support what you are 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']; } 

Usage example:

 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, everything in the array will override the default values. This is possible with array_merge() , which concatenates two arrays, overriding the first array with any repeating elements in the second array.

+51
May 15 '12 at 8:53
source share

Unfortunately this is not possible. To get around this, I would suggest adding the following line to your function:

 $param1 = (is_null ($param1) ? 'value1' : $param1); 

Then you can call it like this:

 funcName (null, 'non default'); Result: value1 non default 
+12
May 15 '12 at 8:50
source share

A simple solution to your problem, instead of using:

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

Use the following syntax:

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

Example:

 function setHeight2($maxheight,$minheight = 50) { echo "The MAX height is : $maxheight <br>"; echo "The MIN height is : $minheight <br>"; } setHeight2(350,250); setHeight2(350); // will use the default value of 50 
+1
Dec 01 '14 at 20:27
source share



All Articles