How to use function's default parameter in PHP

42 Views Asked by At

I want to do something like this.

function add($num1, $num2 = 1) {
    return $num1 + $num2;
}

$bool = true; // Can be true or false

if($bool) {
    add(5, 5);
} else {
    add(5);
}

I was asking me, if it is possible to write this logic in one line like, without repeating the default value:

add(5, $bool ? 5 : USE_DEFAULT_PARAMETER);
2

There are 2 best solutions below

0
M. Eriksson On BEST ANSWER

If you pass in a second argument, then it can't default back to the default value.

However, you could set the default to null, and replace it with 1 in the code:

/**
 * @param int $num1
 * @param ?int $num2 If null or omitted, it will get the value 1
 *
 * @return int
 */
function add($num1, $num2 = null) {
    // If the default value is null, set it to the default
    $num2 = $num2 ?? 1;
    
    return $num1 + $num2;
}

Now you can call it like this:

add(5, $bool ? 5 : null);

Here's a demo: https://3v4l.org/OAQrk

2
Jimmy Found On

This does not look like a good practice. First even if this was possible, you do not have the variable $bool always defined. You might want to use the function somewhere, where $bool does not exist. The correct way would be to use the default parameter in the return statement:

function add (int $num1, ?int $num2 = null): int
{
    return $num1 + ($num2 ?? DEFAULT_PARAMETER);
}

and when you want to call this function, you do this:

$number1 = 5;
$number2 = 5;

$addDefaultValue = true;

$returnedValue = add($number1, !$addDefaultValue ? $number2 : null);