Reputation: 18273
Is there in PHP a shorthand for:
function a() {...}
function b() {...}
$c = a();
$c = ($c) ? $c : b();
In javascript you can simply do:
$c = a() || b();
but in PHP, if you do this, $c
will be a boolean
(which is normal, but I want to know if there exists another shorthand which does what I want).
UPDATE
Thank you guys for all the answers.
The shortest way to do it seems to be:
$c = a() ?: b();
I personally also like:
$c = a() or $c = b();
for the good readability.
Upvotes: 0
Views: 88
Reputation: 13273
It is not possible to do it like in Javascript, but you can use the short version of the ternary construct:
$c = a() ?: b();
Another way is to use or
's lesser precedence. It is not as pretty, but it actually comes closer to how you can do it in Javascript:
$c = a() or $c = b();
Another way of representing the above, so that it is easier to understand, is to wrap it in parentheses:
($c = a()) or ($c = b());
The assignment operator, =, has greater precedence than the "or" operator (do not confuse it with the ||
operator, though), which means that the part after or
will not be executed if the first part evaluates to true
. It is essentially the same as this:
if ($c = a()) {
// Do nothing
} elseif ($c = b()) {
// Do nothing
}
Both expressions are assignments that evaluate to either true
or false
. If the first expression is true
then $c
will be a()
. Otherwise the second expression will be be tried, and because it is the last expression, and because nothing is done after that, $c
will just be equal to b()
.
In any case, this is not really an important problem. If you use time on worrying about the aesthetics of variable assignment then you are not worrying about the right things.
Upvotes: 2
Reputation: 7821
You can use the assignment operator to your benefit.
($c = a()) || ($c = b());
echo $c;
Here's a demo : http://codepad.org/kqnKv2y4
Upvotes: 1
Reputation: 8591
There is possibility to use black magic like this. I’d prefer to write it in longer form though.
function a() {
return false;
}
function b() {
return true;
}
($c = a()) || ($c = b());
echo $c;
Upvotes: 1
Reputation: 1772
I'm assuming that you are looking for this.
http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
$c = a() ? $c : b();
I'm not sure what you're going for though.
Upvotes: -1
Reputation: 449
I like it this way, but its a question of preference
if( !$c=a() ){
$c=b();
}
as in
if(!$User=$db->getUserFromID($user_id)){
$User=$db->getUserFromUsername($username);
}
Upvotes: 1