【问题标题】:Is there a shorter syntax for the ternary operator in php?php中的三元运算符有更短的语法吗?
【发布时间】:2016-07-15 18:05:48
【问题描述】:

如何创建更短的表达式:

$variable = @$array["property"] ? $array["property"] : DEFAULT_VALUE_CONSTANT;

这样的:

$variable = @$array["property"] || DEFAULT_VALUE_CONSTANT;

现在我得到true / false

【问题讨论】:

  • 更短?为什么要更短?
  • @JayBlanchard 因为测试要设置的属性是返回的属性。这对我来说似乎是多余的。
  • 空合并? PHP 7 => php.net/manual/en/language.operators.comparison.php $a ?? $b ?? $c
  • 是的,但是@Fred-ii- 你的 PHP 版本需要是 >=7。再次质疑为什么要抑制错误,而不是使用isset 函数
  • 显然,现在可以在 PHP7 中使用 Null Coalescing 运算符。

标签: php syntax conditional-statements


【解决方案1】:

是的,在 PHP7 中可以使用 Null coalescing operator (??)

$variable = $array["property"] ?? DEFAULT_VALUE_CONSTANT;

如果您使用的是 PHP 版本 elvis operator

$variable = $array["property"] ?: DEFAULT_VALUE_CONSTANT;

请避免使用@ 而不是isset()

参考资料:

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

【讨论】:

  • 是的 @fred-ii- 对此发表了评论。但我的托管服务提供商目前支持 5.6.7。我想我能做的不多。
  • @KristosAthanasiadis 猫王接线员怎么样? $array["property"] ?: DEFAULT_VALUE_CONSTANT;
  • 你是绝对正确的。这就是我要找的接线员!你能编辑你的答案吗?
  • 谢谢!它按预期工作,是的,不需要错误抑制
  • 最后需要抑制@(所以部分忽略前面的评论)否则我需要使用完整的三元运算符,因为如果我使用 isset(),我会得到一个 true | false 结果,而不是测试要设置的变量
猜你喜欢
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 2012-10-01
  • 2021-10-27
  • 2013-04-13
相关资源
最近更新 更多