【问题标题】:php ternary operator giving an errorphp三元运算符给出错误
【发布时间】:2013-06-24 05:38:44
【问题描述】:

在 PHP 中,如果我有这样的三元组:

$my_thing = $this->myAttribute ? $this->myAttribute : "No attribute was set.";

可以这样缩写吗?

$my_thing = $this->myAttribute ?: "No attribute was set."

我以为我记得 PHP 在其三元组中支持这一点,但现在我遇到了一个错误。

【问题讨论】:

  • 你用的是什么版本的php?
  • 可以这样缩短,但如果$this->myAttribute 不存在,您仍然会收到通知。 “得到错误”究竟是什么意思?
  • "但现在我遇到了错误" --- 那你为什么不分享呢?我们应该猜测吗?

标签: php if-statement ternary-operator


【解决方案1】:

它在 PHP 5.3 及更高版本中受支持。来自PHP.net

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

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 2021-05-25
    • 2017-05-15
    • 1970-01-01
    • 2021-09-07
    • 2018-04-11
    相关资源
    最近更新 更多