I have a PHP function that takes three arguments, where one is an optional argument.
function theRange($min, $max) {
// Function Body
}
But I have to set the limit to a default parameter and give it as an optional parameter. So, what I did is:
function theRange($min, $max = 5) {
// Function Body
}
The problem comes when the $min
is greater than 5
and the value becomes invalid if the maximum is lesser the the minimum value. So, I default the $max
to $min
, so what I did is:
function theRange($min, $max = $min) {
// Function Body
}
This throws an error as below:
Parse error: syntax error, unexpected
'$min'
(T_VARIABLE
) in functions.php on line 2.
I am currently handling it this way:
function theRange($min, $max = null) {
if (!isset($max) || is_null($max))
$max = $min;
// Function Body
}
Is there a better way to handle this default parameter, to have the previous parameter as an input scenario? Thanks in advance! :)
Simply assign default value, and check if it's valid inside function:
function theRange($min, $max = 5) {
$max = $min > $max ? $min : $max;
}