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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1993409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:34:22  来源:igfitidea点击:

?: operator (the 'Elvis operator') in PHP

phpcoding-styleconditional-operatorlanguage-construct

提问by alpha_juno

I saw this today in some PHP code:

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

$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?

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

回答by BalusC

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 barwill only be evaluated once.

bar只会评估一次的差异。

You can also use this to do a "self-check" of fooas demonstrated in the code example you posted:

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

foo = foo ?: bar;

This will assign barto fooif foois null or falsey, else it will leave foounchanged.

这将分配barfooiffoo为 null 或 falsey,否则它将foo保持不变。

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.

顺便说一下,它被称为Elvis operator

Elvis operator

猫王接线员

回答by Yacoby

See the docs:

查看文档

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3returns expr1if expr1evaluates to TRUE, and expr3otherwise.

自 PHP 5.3 起,可以省略三元运算符的中间部分。如果计算结果为,则表达式expr1 ?: expr3返回,否则返回。expr1expr1TRUEexpr3

回答by voodoo417

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 the future (in PHP 7) operator Null Coalesce Operatorwill do it, for example:

来自 RFC。将来(在 PHP 7 中)operator Null Coalesce Operator会这样做,例如:

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

回答by Prasad Paradkar

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).

另一个重要的考虑因素:Elvis Operator 破坏了 Zend Opcache 标记化过程。我发现这很难!虽然这可能已在更高版本中修复,但我可以确认这个问题存在于 PHP 5.5.38(内置 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!

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

回答by Atli

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.

是的,这是 PHP 5.3 中的新功能。如果它被评估为 TRUE,则它返回测试表达式的值,如果它被评估为 FALSE,则返回替代值。