开发者

PHP equivalent for Ruby's or-equals (foo ||=bar)?

开发者 https://www.devze.com 2023-01-09 15:22 出处:网络
In PHP I often write lines like isset($foo)? NULL : $foo = \'bar\' In ruby there is a brilliant shortcut for that, called or equals

In PHP I often write lines like

isset($foo)? NULL : $foo = 'bar'

In ruby there is a brilliant shortcut for that, called or equals

foo ||= 'bar'

Does PHP have such an operator, shortcut or method call? I cannot find one, but I might have missed i开发者_如何学运维t.


As of PHP7, you can use the Null Coalesce Operator:

The coalesce, or ??, operator is added, which returns the result of its first operand if it exists and is not NULL, or else its second operand.

So you can write:

$foo = $foo ?? 'bar';

and it will use $foo if it is set and not null or assign "bar" to $foo.

On a sidenote, the example you give with the ternary operator should really read:

$foo = isset($foo) ? $foo : 'bar';

A ternary operation is not a shorthand if/else control structure, but it should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution


I really like the ?: operator. Unfortunately, it is not yet implemented on my production environment. So, if I were to make this look ruby-ish, I would go for something like:

isset($foo) || $foo = 'bar';

Or, if you want it even shorter (slower, and may yield unexpected results):

@$foo || $foo = 'bar';


You could create your own function:

function setIfNotSet(&$var, $value) {
    if(!isset($var)) {
        $var = $value;
    }
}


I find it readable, concise and performant to just do:

isset($foo) or $foo = 'bar';


As of PHP 5.3 it's possible to use $foo ?: 'bar' Unless you expect $foo to be false

[edit]

Forget it. It still raises E_NOTICE if $foo is no set.


From the manual:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

It's not exactly the same though. Hope it helps anyway.


No. According to w3schools, that operator doesn't exist.

Also, the PHP code you posted is rather cryptic. I prefer something like this:

if (!isset($foo)) $foo = 'bar';


The most similar with ruby is this:

$foo or $foo = 'bar';

$foo is false if

$foo = 0;
$foo = '0';
$foo = NULL;
$foo = '';
$foo = array();
$foo = FALSE;
0

精彩评论

暂无评论...
验证码 换一张
取 消