当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Declare variable with condition

问题描述:

var foo, bar;

foo = 'hello'; // first

bar = 'world'; // otherwise

var baz = foo || bar;

console.log(baz);

wondering whats the PHP way of doing the above? I already know about the ternary operator:

$foo = $bar = '';

$foo = 'hello'; // first

$bar = 'world'; // otherwise

$baz = $foo ? $foo : $bar;

echo $baz;

.. but I'm looking to optimize here because the $foo in my case is MySQL query and I believe its executed twice(?) on check and then on assignment. Either way, I want to know if there's a more elegant DRY method of doing it.

Edit:

In PHP7 you can do:

$baz = $foo ?? $bar;

... but looking for something in PHP 5+

网友答案:

For this specific case, PHP provides a ?: shorthand, which only evaluates the condition once:

$baz = $foo ?: $bar;

But apart from that it's functionally equivalent to $foo ? $foo : $bar.

EDIT: $foo ?? $bar is only for when $foo may be null. That operator is only available since PHP 7. ?: however is available since PHP 5.3. The ternary will check for false (loosely).

分享给朋友:
您可能感兴趣的文章:
随机阅读: