Elvis Operator (?:) Unraveled in PHP
In the depths of a complex PHP codebase, you may encounter a mysterious operator: the ?: operator. Dubbed the "Elvis operator," it may have you wondering, "What's its purpose?"
The ?: operator, in essence, evaluates to its left operand if the left operand is considered "truthy," and the right operand otherwise. In other words:
foo ?: bar
is roughly equivalent to the ternary operator:
foo ? foo : bar
or in a traditional if-else statement:
if (foo) { foo = foo; } else { foo = bar; }
However, unlike the ternary operator, the ?: operator evaluates the left operand only once, enhancing efficiency.
Example Usage
One common use case is for self-checking, as seen in the code snippet:
$items = $items ?: $this->_handle->result('next', $this->_result, $this);
Here, it assigns the result of $this->_handle->result() to $items if $items is null or falsey, while leaving $items unchanged otherwise.
Additional Examples
Here are a few more examples to illuminate the behavior:
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' var_dump('' ?: 'roll'); // 'roll' var_dump('0' ?: 'roll'); // 'roll' var_dump('42' ?: 'roll'); // '42'
Should you encounter a ?: operator in the future, remember that its goal is to provide a concise way to evaluate and assign based on truthiness, making your code more efficient and readable.
以上是什么是 Elvis 运算符 (?:) 以及它在 PHP 中如何工作?的详细内容。更多信息请关注PHP中文网其他相关文章!