PHP 中的 ?: 运算符(“Elvis 运算符”)

发布于 2024-08-17 06:53:37 字数 219 浏览 9 评论 0原文

我今天在一些 PHP 代码中看到了这一点:

$items = $items ?: $this->_handle->result('next', $this->_result, $this);

我不熟悉这里使用的 ?: 运算符。它看起来像一个三元运算符,但省略了谓词是否为 true 时计算的表达式。这是什么意思?

I saw this today in some PHP code:

$items = $items ?: $this->_handle->result('next', $this->_result, $this);

I'm not familiar with the ?: operator being used here. It looks like a ternary operator, but the expression to evaluate to if the predicate is true has been omitted. What does it mean?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

再见回来 2024-08-24 06:53:37

如果左操作数是 ,否则为正确的操作数。

在伪代码中,

foo = bar ?: baz;

大致解析为

foo = bar ? bar : baz;

或 ,

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

区别在于 bar 只会被评估一次。

您还可以使用它对 foo 进行“自检”,如您发布的代码示例中所示:

foo = foo ?: bar;

这会将 bar 分配给 foo > 如果 foo 为 null 或 falsey,否则它将保持 foo 不变。

更多示例:

<?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'
    var_dump('' ?: 'roll'); //  'roll'
    var_dump('0' ?: 'roll'); //  'roll'
    var_dump('42' ?: 'roll'); //  '42'
?>

顺便说一下,它被称为 Elvis 运算符

埃尔维斯操作员

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'
    var_dump('' ?: 'roll'); //  'roll'
    var_dump('0' ?: 'roll'); //  'roll'
    var_dump('42' ?: 'roll'); //  '42'
?>

By the way, it's called the Elvis operator.

Elvis operator

峩卟喜欢 2024-08-24 06:53:37

请参阅文档

从 PHP 5.3 开始,可以省略三元运算符的中间部分。如果 expr1 计算结果为 TRUE,则表达式 expr1 ?: expr3 返回 expr1,并且 <代码>expr3 否则。

See the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

陪你搞怪i 2024-08-24 06:53:37

小心数组。我们必须在 ? 之后编写一个检查变量,因为:

  $params = ['param1' => 'value1',
             'param2' => 'value2',
             'param3' => 'value3',];

  $param1 = isset($params['param1'])?:null;
  $param2 = !empty($params['param2'])?:null;
  $param3 = $params['param3']?:null; // get E_NOTICE, if $params['param3'] eq false

  var_dump($param1,$param2,$param3);
  true // would like to expect `value1`
  true // would like to expect `value2`
  param3 // properly, but problem above

更新

来自 RFC。在 PHP 7 中,运算符 空合并运算符 将执行此操作,例如:

$param1 = $params['param1'] ?? null;
// Equivalent to:  $param1 = isset($params['param1']) ? $params['param1'] : null;

Be careful with arrays. We must write a checking variable after ?, because:

  $params = ['param1' => 'value1',
             'param2' => 'value2',
             'param3' => 'value3',];

  $param1 = isset($params['param1'])?:null;
  $param2 = !empty($params['param2'])?:null;
  $param3 = $params['param3']?:null; // get E_NOTICE, if $params['param3'] eq false

  var_dump($param1,$param2,$param3);
  true // would like to expect `value1`
  true // would like to expect `value2`
  param3 // properly, but problem above

Updated

From RFC. In PHP 7 the operator Null Coalesce Operator will do it, for example:

$param1 = $params['param1'] ?? null;
// Equivalent to:  $param1 = isset($params['param1']) ? $params['param1'] : null;
生生不灭 2024-08-24 06:53:37

Elvis 运算符:

?: 是 Elvis 运算符。这是一个二元运算符,它执行以下操作:

?: 的左侧值强制转换为布尔值,并检查它是否为true。如果 true 它将返回左侧的表达式,如果 false 它将返回右侧的表达式。

示例:

var_dump(0 ?: "Expression not true");     // expression returns: Expression not true
var_dump("" ?: "Expression not true");    // expression returns: Expression not true
var_dump("hi" ?: "Expression not true");  // expression returns string hi
var_dump(null ?: "Expression not true");  // expression returns: Expression not true
var_dump(56 ?: "Expression not true");    // expression return int 56

何时使用:

Elvis 运算符基本上是三元运算符特定情况的简写语法,即:

$testedVar ? $testedVar : $otherVar;

Elvis 运算符将通过以下方式使语法更加简洁:

$testedVar ?: $otherVar;

Elvis operator:

?: is the Elvis operator. This is a binary operator which does the following:

Coerces the value left of ?: to a boolean and checks if it is true. If true it will return the expression on the left side, if false it will return the expression on the right side.

Example:

var_dump(0 ?: "Expression not true");     // expression returns: Expression not true
var_dump("" ?: "Expression not true");    // expression returns: Expression not true
var_dump("hi" ?: "Expression not true");  // expression returns string hi
var_dump(null ?: "Expression not true");  // expression returns: Expression not true
var_dump(56 ?: "Expression not true");    // expression return int 56

When to use:

The Elvis operator is basically shorthand syntax for a specific case of the ternary operator which is:

$testedVar ? $testedVar : $otherVar;

The Elvis operator will make the syntax more consise in the following manner:

$testedVar ?: $otherVar;
内心激荡 2024-08-24 06:53:37

另一个重要的考虑因素:Elvis Operator 破坏了 Zend Opcache 标记化过程。我发现这很难!虽然这可能已在更高版本中得到修复,但我可以确认 PHP 5.5.38 中存在此问题(带有内置 Zend Opcache v7.0.6-dev)。

如果您发现某些文件“拒绝”缓存在 Zend Opcache 中,这可能是原因之一...希望这会有所帮助!

Another important consideration: The Elvis Operator breaks the Zend Opcache tokenization process. I found this the hard way! While this may have been fixed in later versions, I can confirm this problem exists in PHP 5.5.38 (with in-built Zend Opcache v7.0.6-dev).

If you find that some of your files 'refuse' to be cached in Zend Opcache, this may be one of the reasons... Hope this helps!

々眼睛长脚气 2024-08-24 06:53:37

是的,这是 PHP 5.3 中的新功能。如果计算结果为 TRUE,则返回测试表达式的值;如果计算结果为 FALSE,则返回替代值。

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

忘你却要生生世世 2024-08-24 06:53:37

我认为目的是条件执行:

$a ?: func(); 

仅当 $a 的值解析为 FALSE 时才会执行 func() 中的结果。它可以用作

if(!$a){
    func();
}

thre赋值是可选的 $a = $a ?: func() 的缩写,类似于:

if(!$a){
    $a = func();
}

i think the purpose is conditional execution:

$a ?: func(); 

results in func() will only be executed if $a has a value that would resolve to FALSE. it may be used used as a short for

if(!$a){
    func();
}

thre assignment is optional $a = $a ?: func() is like:

if(!$a){
    $a = func();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文