【问题标题】:PHP: Please help explain these ternary operatorsPHP:请帮助解释这些三元运算符
【发布时间】:2021-02-26 21:56:08
【问题描述】:

谁能解释一下这个运算符?我意识到它现在在 7.4 中已弃用,因此进行了重构。

这个例子:

if ($this->interestAreas()->count() > 0) {
    $ids ?: $ids = $this->interestAreas()->pluck('id');
    $this->interestAreas()->detach();
}

?: 用于分配变量时,我明白这一点,例如:$newUser = ($user) :? null;,但不是如上所述。谁能解释一下如何重写?

【问题讨论】:

  • 意义相同,只是他们没有在作业中使用结果。
  • 这只是if 声明的简写。
  • 是什么让你说它已被弃用?
  • 谢谢@Barmar - 我在应用程序中遇到类似用途的错误,但也许这种用途实际上是有效的......Unparenthesized a ?: b ? c : d` 已弃用`。
  • 7.4 不推荐使用不带括号的嵌套三元组。这与 elvis 运算符无关。

标签: php operators elvis-operator


【解决方案1】:

?: 想象成条件变量,类似字符串

$a = 1 ? $b : $c;

可以这样读:

If $a equals 1 then show $b, if not show $c;

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2016-07-18
    • 2014-01-11
    相关资源
    最近更新 更多