PHP 使变量回退到默认值的简短语句
PHP short statement to make variable fallback to default
我们知道,如果我们使用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';
以上任何一个,我觉得都不整齐。
而且我盲目地寻找任何答案,寻找语句或内置函数来简化工作。但是找了很多方法都没有找到答案。
所以请帮忙。
在 $a 未定义时执行 $a 仍然会报错。不幸的是,处理变量时唯一正确的方法是:
echo isset($a) ? $a: 'default';
在处理long函数的时候,还是要检查你要检查的条件,因为如果返回false,你还是会陷入default。
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 解释为错误。您可以查看完整列表 here.
为什么不尝试反过来,先将变量设置为默认值?
$a = "default";
...
echo $a;
那么你不需要检查它是否被设置 - 只需使用变量。
这有额外的好处,它可以防止使用未分配变量的问题(不幸的是非常普遍,并且可能难以追踪)。
关于这个问题: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 ?: expr3 returns 如果 expr1 的计算结果为 TRUE,则为 expr1,否则为 expr3。
参见:http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
我们知道,如果我们使用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';
以上任何一个,我觉得都不整齐。
而且我盲目地寻找任何答案,寻找语句或内置函数来简化工作。但是找了很多方法都没有找到答案。
所以请帮忙。
在 $a 未定义时执行 $a 仍然会报错。不幸的是,处理变量时唯一正确的方法是:
echo isset($a) ? $a: 'default';
在处理long函数的时候,还是要检查你要检查的条件,因为如果返回false,你还是会陷入default。
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 解释为错误。您可以查看完整列表 here.
为什么不尝试反过来,先将变量设置为默认值?
$a = "default";
...
echo $a;
那么你不需要检查它是否被设置 - 只需使用变量。
这有额外的好处,它可以防止使用未分配变量的问题(不幸的是非常普遍,并且可能难以追踪)。
关于这个问题: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 ?: expr3 returns 如果 expr1 的计算结果为 TRUE,则为 expr1,否则为 expr3。
参见:http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary