It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.
In pseudocode,
foo = bar ?: baz;
roughly resolves to
foo = bar ? bar : baz;
or
if (bar) {
foo = bar;
} else {
foo = baz;
}
with the difference that bar
will only be evaluated once.
You can also use this to do a "self-check" of foo
as demonstrated in the code example you posted:
foo = foo ?: bar;
This will assign bar
to foo
if foo
is null or falsey, else it will leave foo
unchanged.
Some more examples:
<?php
var_dump(5 ?: 0); // 5
var_dump(false ?: 0); // 0
var_dump(null ?: 'foo'); // 'foo'
var_dump(true ?: 123); // true
var_dump('rock' ?: 'roll'); // 'rock'
?>
By the way, it's called the Elvis operator.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…