phpsyntaxdefault-valuesyntactic-sugar

How to use function's default parameter in PHP


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

Solution

  • 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