问题
What's a nicer way to do the following, that doesn't call f() twice?
$x = f() ? f() : 'default';
回答1:
In PHP 5.3, you can also do:
$a = f() ?: 'default';
See the manual on ?: operator.
回答2:
This seems to work fine:
$x = f() or $x = 'default';
回答3:
function f()
{
// conditions
return $if_something ? $if_something : 'default';
}
$x = f();
回答4:
$x = ($result = foo()) ? $result : 'default';
test
回答5:
You could save it to a variable. Testcase:
function test() {
echo 'here';
return 1;
}
$t = test();
$x = $t ? $t : 0;
echo $x;
来源:https://stackoverflow.com/questions/4832114/php-assignment-with-a-default-value