,如果我们使用的是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';
以上任何一项,我认为都不整洁。
而且我盲目地找到任何答案,找不到一个语句或内置函数来简化工作。但是在尝试了很多方法之后,我找不到答案。
所以请帮忙。
关于这个问题:http://php.net/manual/en/language.operators.logical.php#115208
因此,请参阅三元运算符的文档,可以使用:
echo $a ?: 'defaults for a';
如果 expr1 的计算结果为 TRUE,则表达式 (expr1) ? (expr2) : (expr3)
计算结果为 expr2,如果 expr1 的计算结果为 FALSE,则表达式的计算结果为 expr3。
从 PHP 5.3 开始,可以省略三元运算符的中间部分。表达式 expr1 ?:如果 expr1 的计算结果为 TRUE,则 expr3 返回 expr1,否则返回 expr3。
请参阅:http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
在未定义$a时执行$a仍然会给您带来错误。不幸的是,在处理变量时唯一正确的方法是:
echo isset($a) ? $a: 'default';
在处理 long 函数时,你仍然需要检查你想要检查的条件,因为如果它返回 false,你仍然会陷入默认值。
var $result = we_made_many_calculation_here_and_this_is_the_result(); // false
echo $result ? $result : 'default'; // echos default
你需要:
var $result = we_made_many_calculation_here_and_this_is_the_result();
echo !is_null($result) ? $result : 'default';
这是php解释为错误的可悲限制。您可以在此处查看完整列表。
为什么不尝试反过来做,并从将变量设置为其默认值开始呢?
$a = "default";
...
echo $a;
然后你不需要检查它是否设置了 - 只需使用变量。
这有一个额外的好处,那就是它可以防止使用未赋值变量的问题(不幸的是非常常见,并且可能很难追踪(。