3

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?

4

1 回答 1

7

它只被调用一次。

如果您在函数中添加副作用(例如打印),这很容易看出,例如:

<?php
function get_name() {
    print("get_name() was called\n");
    return "somestring";
}

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

演示

于 2018-09-30T20:46:28.197 回答