设置默认值(条件分配) [英] Setting default values (conditional assignment)
本文介绍了设置默认值(条件分配)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中,您可以轻松地为变量设置默认值
In Ruby you can easily set a default value for a variable
x ||= "default"
如果x为nil或false,则上述语句会将x的值设置为默认"
The above statement will set the value of x to "default" if x is nil or false
PHP中是否有类似的快捷方式,还是我必须使用更长的形式?
Is there a similar shortcut in PHP or do I have to use the longer form:
$x = (isset($x))? $x : "default";
有没有更简单的方法可以在PHP中处理此问题?
Are there any easier ways to handle this in PHP?
推荐答案
从PHP 5.3开始,您可以使用三元运算符,而忽略中间参数:
As of PHP 5.3 you can use the ternary operator while omitting the middle argument:
$x = $x ?: 'default';
这篇关于设置默认值(条件分配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文