【问题标题】:How to evaluate function only once in ternary operators?如何在三元运算符中只评估一次函数?
【发布时间】:2014-01-26 15:43:58
【问题描述】:

我想知道我是否可以制作一个单行三元运算符来检查函数返回的值并使用它?

让我们检查一下这个示例(PHP)代码:

return get_db_row($sql_parameters) ? get_db_row($sql_parameters) : get_empty_row();

我的目的是返回 get_db_row() ,但如果它是空的,则返回一个空行。

但是,我认为,这条线路会调用get_db_row()两次。对吗?

我想调用一次。一种解决方案是将返回值存储在这样的变量中:

$row = get_db_row($sql_parameters);
return $row ? $row : get_empty_row();

但是我可以一行完成吗?

类似:

return ($row = get_db_row()) ? $row : get_empty_row();

有可能吗?

感谢您的帮助!

【问题讨论】:

  • 您的最后一个示例应该可以正常工作。您将 get_db_row() 的结果分配给 $row 变量并同时对其进行评估。你试过了吗?这是查看它是否有效的最佳方法。

标签: php performance memory ternary-operator


【解决方案1】:

你说得对。以下行只会调用该函数一次:

return ($row = get_db_row()) ? $row : get_empty_row();

一些代码来证明这一点:

$counter = 0;
function test() {
    global $counter;
    $counter++;
    return true;
}

$var = ($ret = test()) ? $ret : 'bar';
echo sprintf("#1 called the function %d times\n", $counter);

$counter = 0;
$var = ($ret = test()) ? test() : 'bar';
echo sprintf("#2 called the function %d times", $counter);

输出:

#1 called the function 1 times
#2 called the function 2 times

Demo.

【讨论】:

    【解决方案2】:
    return get_db_row($sql_parameters) ?: get_empty_row();
    

    如果您运行的是不支持此功能的早期版本的 PHP...

    return ($x = get_db_row($sql_parameters)) ? $x : get_empty_row();
    

    应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2023-01-20
      • 2020-07-22
      相关资源
      最近更新 更多