【发布时间】:2015-09-26 14:57:50
【问题描述】:
我们知道,如果我们使用 javascript 或 python,我们可以使用下面的语句来获取一个变量,或者它的默认值。
// javascript
alert(a || 'default');
# python
print(a or 'default');
在 php 中,我们可能需要调用以下代码:
echo $a ? $a : 'default';
如果 $a 是一个很长的语句,情况就更糟了:
echo (
we_made_many_calculation_here_and_this_is_the_result() ?
we_made_many_calculation_here_and_this_is_the_result() :
'default'
);
或
var $result = we_made_many_calculation_here_and_this_is_the_result();
echo $result ? $result : 'default';
以上任何一个,我都觉得不整齐。
而且我也找不到任何答案,找不到语句或内置函数来简化工作。但是在尝试了很多方法之后,我找不到答案。
所以请帮忙。
【问题讨论】:
-
echo $result ?: 'default'或许? -
@Andrew Perfect,你教会了我很多东西!谢谢!