Skip to content
Advertisement

PHP optional parameter

I’m kinda confused about optional parameters, or setting a parameter within the function in general. So I found this example:

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

and I don’t understand why echo makecoffe(“espresso”) returns espresso and not cappuccino. Wouldn’t espresso be overwritten when calling the method? In my head $type would first be espresso but would then be set to cappuccino since it happens after calling the method. It’s kind of hard to explain what I mean, but does $type = "cappuccino" only get called when there’s no parameter or why does this happen? Same with

function makecoffee($type = null)
    {
}

echo makecoffe("espresso");

why would this return espresso and not null even though type would be set to null when calling the function?

Advertisement

Answer

That’s because the $param = 'value' bit in the function declaration is not executed every time the function is called.

It only comes into play if you don’t pass a value for that parameter.

Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.

if true === $param holds no value
    $param = 'value'
endif

In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.

Edit: Note that the snippet above is deliberately just pseudo code as it’s tricky to accurately express what’s going using PHP on once PHP has been compiled. See the comments for more info.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement