【问题标题】:Newer style PHP ternary operator has undesired result with isset function较新风格的 PHP 三元运算符使用 isset 函数产生不希望的结果
【发布时间】:2012-01-24 02:30:03
【问题描述】:

我对 PHP 的三元运算符有疑问,从 PHP 5.3 版开始,您可以用更短的版本替换速记三元运算符

// Older version
$route = isset($test) ? $test : 'test is NOT set';


// Newer version as of 5.3
$route = isset($test) ?: 'test is NOT set';

如果没有设置$test,现在在较新的版本上。它工作正常。但是,当由于 isset() 方法设置它时,它返回 true1 而不是值。

我是否必须使用较旧的较长方法才能使$route 等于$test 的值而不是1 的布尔值?

【问题讨论】:

  • 你可以改用$route = $test ?: 'test is NOT set';
  • 如果您不介意隐藏错误消息,您仍然可以使用速记。这不是“正确”或“漂亮”的方法,但仍然有效 - $route = @$test ?: 'test is NOT set';

标签: php


【解决方案1】:

你必须使用更长的版本。

引用docs

表达式 expr1 ?:如果 expr1 的计算结果为 TRUE,则 expr3 返回 expr1,否则返回 expr3。

因此,您的速记版本的正确行为是返回评估 isset($test) 的结果。不是你想要的$test

【讨论】:

    【解决方案2】:

    PHP 7 开始,您可以使用 null 合并运算符

    $route = $test ?? 'test is NOT set';
    

    相当于

    $route = isset($test) ? $test : 'test is NOT set';
    

    Here你可以找到一些细节:

    已添加空合并运算符 (??) 作为语法糖,用于需要将三元组与 isset() 结合使用的常见情况。如果存在且不为 NULL,则返回其第一个操作数;否则返回第二个操作数。

    【讨论】:

      猜你喜欢
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2017-04-26
      相关资源
      最近更新 更多