Search code examples
phpphp-7null-coalescing-operator

Does null coalescing operator call a function twice?


The null coalescing operator (??) returns its first operand if it exists and is not NULL, and otherwise returns its second operand.

If the first operand is a function or method call, does the operator call the function call twice?

As an example, say the function get_name() returns a string value or null.

$name = get_name() ?? 'no name found';

So is get_name() called once and the value stored ready to assign it to the variable ($name) or when the ?? is activated due to the function returning a value that is true for isset(), does ?? call on the first operand a second time to get the value?


Solution

  • It's only called once.

    This is quite easy to see if you add a side effect to your function, such as printing, e.g.:

    <?php
    function get_name() {
        print("get_name() was called\n");
        return "somestring";
    }
    
    $name = get_name() ?? 'no name found';
    print($name);
    ?>
    

    Demo