【问题标题】:PHP short statement to make variable fallback to default [duplicate]PHP简短语句使变量回退到默认值[重复]
【发布时间】: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,你教会了我很多东西!谢谢!

标签: php function syntax


【解决方案1】:

与此问题相关: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

【讨论】:

  • 但请记住,非空字符串 '0' 的计算结果为 FALSE!
【解决方案2】:

当 $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 解释为 false 的一个可悲的限制。您可以查看完整列表here.

【讨论】:

  • 我正在寻找一种方法来缩短它,而不是让它变好。不过谢谢。
  • 在 php 中,我认为您会看到更多这些语句发生在单独的行上,而不是在您回显它的同一行上。您必须根据语言以不同的方式思考和编写代码。 PHP 不像其他语言那样支持简写。
  • 谢谢,但?: 运算符正是我想要的。
【解决方案3】:

为什么不尝试反过来做,然后将变量设置为其默认值?

$a = "default";
...
echo $a;

那么您无需检查它是否已设置 - 只需使用变量即可。

这有额外的好处,然后防止使用未分配变量的问题(不幸的是非常常见,并且可能难以追踪)。

【讨论】:

  • 谢谢,但?: 运算符正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2012-06-25
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2020-12-03
  • 2014-05-06
相关资源
最近更新 更多