Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading