PHP assignment with a default value
What's a nicer way to do the following, that doesn't c开发者_如何转开发all f() twice?
$x = f() ? f() : 'default';
In PHP 5.3, you can also do:
$a = f() ?: 'default';
See the manual on ?: operator.
This seems to work fine:
$x = f() or $x = 'default';
function f()
{
// conditions
return $if_something ? $if_something : 'default';
}
$x = f();
$x = ($result = foo()) ? $result : 'default';
test
You could save it to a variable. Testcase:
function test() {
echo 'here';
return 1;
}
$t = test();
$x = $t ? $t : 0;
echo $x;
精彩评论