问题
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