php 给变量一个默认值的最佳方法(模拟 Perl ||, ||= )
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5972516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to give a variable a default value (simulate Perl ||, ||= )
提问by Tom Auger
I love doing this sort of thing in Perl: $foo = $bar || $baz
to assign $baz
to $foo
if $bar
is empty or undefined. You also have $foo ||= $bletch
which will only assign $bletch
to $foo
if $foo
is not defined or empty.
我喜欢在 Perl 中做这种事情:$foo = $bar || $baz
分配$baz
给$foo
if$bar
是空的或未定义的。您还有$foo ||= $bletch
which 只会分配$bletch
给$foo
if$foo
未定义或为空。
The ternary operator in this situation is tedious and tiresome. Surely there's a simple, elegant method available in PHP?
这种情况下的三元运算符既乏味又令人厌烦。PHP 中肯定有一个简单、优雅的方法吗?
Or is the only answer a custom function that uses isset()?
还是唯一的答案是使用 isset() 的自定义函数?
采纳答案by jpschroeder
In PHP 7 we finally have a way to do this elegantly. It is called the Null coalescing operator. You can use it like this:
在 PHP 7 中,我们终于有办法优雅地做到这一点。它被称为Null 合并运算符。你可以这样使用它:
$name = $_GET['name'] ?? 'john doe';
This is equivalent to
这相当于
$name = isset($_GET['name']) ? $_GET['name']:'john doe';
回答by BoltClock
PHP 5.3 has a shorthand ?:
operator:
PHP 5.3 有一个速记?:
运算符:
$foo = $bar ?: $baz;
Which assigns $bar
if it's not an empty value (I don't know how this would be different in PHP from Perl), otherwise $baz
, and is the same as this in Perl and older versions of PHP:
$bar
如果它不是空值(我不知道这在 PHP 中与 Perl 有何不同),则分配,否则$baz
,与 Perl 和旧版本 PHP 中的相同:
$foo = $bar ? $bar : $baz;
But PHP does not have a compound assignment operator for this (that is, no equivalent of Perl's ||=
).
但是 PHP 没有用于此的复合赋值运算符(即,没有 Perl 的等价物||=
)。
Also, PHP will make noise if $bar
isn't set unless you turn notices off. There is also a semantic difference between isset()
and empty()
. The former returns false if the variable doesn't exist, or is set to NULL
. The latter returns true if it doesn't exist, or is set to 0
, ''
, false
or NULL
.
此外,$bar
除非您关闭通知,否则PHP 会在未设置时发出噪音。isset()
和之间也存在语义差异empty()
。如果变量不存在或设置为 ,则前者返回 false NULL
。如果后者不存在,或者设置为0
、''
、false
或,则返回 true NULL
。
回答by Tom Auger
Thanks for all the great answers!
感谢所有伟大的答案!
For anyone else coming here for a possible alternative, here are some functions that help take the tedium out of this sort of thing.
对于来这里寻求可能的替代方案的任何其他人,这里有一些功能可以帮助消除这类事情的乏味。
function set_if_defined(&$var, $test){
if (isset($test)){
$var = $test;
return true;
} else {
return false;
}
}
function set_unless_defined(&$var, $default_var){
if (! isset($var)){
$var = $default_var;
return true;
} else {
return false;
}
}
function select_defined(){
$l = func_num_args();
$a = func_get_args();
for ($i=0; $i<$l; $i++){
if ($a[$i]) return $a[$i];
}
}
Examples:
例子:
// $foo ||= $bar;
set_unless_defined($foo, $bar);
//$foo = $baz || $bletch
$foo = select_defined($baz, $bletch);
I'm sure these can be improved upon.
我相信这些可以改进。
回答by mario
A common idiom to stay compatible with older PHP versions is:
保持与旧 PHP 版本兼容的常见习惯用法是:
$var = $bool or $var = "default";
// If I use it, then only with excessive spaces for clarity.
This works for values that can be evaluated in boolean context. The advantage here is that it also gives you said debug e_notice should the variable be undefined.
这适用于可以在布尔上下文中评估的值。这里的优点是,如果变量未定义,它还会给你说 debug e_notice。
回答by AndreyS Scherbakov
In PHP earlier than 7.*, one may use ?: for an undefined variable having errors locally suppressed with an @
:
在 7.* 之前的 PHP 中,可以将 ?: 用于未定义的变量,该变量的错误在本地被抑制为@
:
$foo = @$bar ?: $baz;
回答by Bassem Shahin
this is another good format for the isset
case
这是isset
案例的另一种好格式
isset($foo) || $foo= $bar;
isset($foo) || $foo= $bar;
another simple way and will give you more control as you can add more conditions and assign to another variable in the same time
另一种简单的方法,将为您提供更多控制,因为您可以添加更多条件并同时分配给另一个变量
$foo = (isset($oData['foo']))?$bar['foo']:'default value';
$foo = (isset($oData['foo']))?$bar['foo']:'default value';
回答by dkellner
A possible solution: defaultFor( )
一个可能的解决方案:defaultFor()
Unless we have a factory solution (which is indeed very annoying), I'd recommend the following little helper. It does the job in most cases:
除非我们有工厂解决方案(这确实很烦人),否则我会推荐以下小帮手。它在大多数情况下可以完成工作:
function defaultFor(&$x,$default=null) {
if(!isset($x)) $x = $default;
}
//-------------------- Now you can do this: --------------
defaultFor($a,"Hyman"); // if $a is not set, it will be "Hyman"
defaultFor($x); // no more notices for $x but keep it !isset
I hope this is close to what you wanted to achieve. It will not give you any notices if you use it with a nonexistent variable, and it's quite convenient. Surely it has a drawback: the default value always gets calculated beforehand so don't use it with anything heavy as a second parameter, like a file_get_contents or something. In those cases, you're better off with isseting.
我希望这接近您想要实现的目标。如果您将它与不存在的变量一起使用,它不会给您任何通知,并且非常方便。当然它有一个缺点:默认值总是事先计算出来的,所以不要将它与任何重要的第二个参数一起使用,比如 file_get_contents 或其他东西。在这些情况下,您最好使用isseting。