给变量一个默认值的最佳方法(模拟 Perl ||, ||= ) [英] Best way to give a variable a default value (simulate Perl ||, ||= )
问题描述
我喜欢用 Perl 做这种事情:$foo = $bar ||如果
将 $bar
为空或未定义,则 $baz$baz
分配给 $foo
.你还有 $foo ||= $bletch
,它只会将 $bletch
分配给 $foo
如果 $foo
未定义或为空.
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.
这种情况下的三元运算符既乏味又令人厌烦.PHP 中肯定有一个简单、优雅的方法吗?
The ternary operator in this situation is tedious and tiresome. Surely there's a simple, elegant method available in PHP?
或者是使用isset()的自定义函数的唯一答案?
Or is the only answer a custom function that uses isset()?
推荐答案
在 PHP 7 中,我们终于有了一种优雅的方法.它被称为空合并运算符.你可以这样使用它:
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:
$name = $_GET['name'] ?? 'john doe';
这相当于
$name = isset($_GET['name']) ? $_GET['name']:'john doe';
这篇关于给变量一个默认值的最佳方法(模拟 Perl ||, ||= )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!