Short way for isset($a) ? $a : 'other'; [duplicate]

十年热恋 提交于 2019-12-25 18:44:10

问题


is there any shorter way for this in PHP?

$b = isset($a) ? $a : 'other';

Like in JS

$b = $a || 'other';

This does not realy look like a big thing, but when you have a large list of properties/keys to check, this becomes annoing.

Thanks in advance :)


回答1:


It is only possible if $a is guaranteed to exist. So in your case it would not be possible, because you seem to not know if $a is set.

$b = isset($a) ? $a : 'other';

But it would be in this case:

public function foo($var)
{
    $var = $var ?: self::DEFAULT;
}



回答2:


A shorter ternary syntax has has been introduced in PHP 5.3. From the documentation:

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.

What you want is however still not (properly) possible with this shorter syntax but requires the coalesce operator to-be introduced in PHP 7.



来源:https://stackoverflow.com/questions/26489096/short-way-for-isseta-a-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!