2014-01-26 48 views
0

我想知道是否可以创建一个单行三元运算符来检查函数返回的值并使用它?如何在三元运算符中仅评估一次函数?

让我们来看看这个例子(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(); 

这可能吗?

感谢您的帮助!

+0

你的最后一个例子应该能正常运行。您将get_db_row()的结果分配给$ row变量并同时对其进行评估。你试过了吗?这是查看它是否有效的最佳方式。 – jd182

回答

3

你说得对。下面的线将只调用函数一次:

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.

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

如果你运行PHP的早期版本不支持此...

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

应该只是罚款。

相关问题