PHP: Multiple statements in a ternary expression
I have a function that looks something like this:
function fun()
{
$pMana < 20 ? error(1) : $pMana -= 20;
//do stuff
}
I want when the error function is called, it also exits the function, something like this
function fun()
{
$pMana < 20 ? (error(1); return) : $pMana -= 20; //invalid syntax
//do stuff
}
I have yet to see a terna开发者_如何学Gory expression able to handle more than one statement like this, but I'm new to this. Is it possible?
Use if
statement in this situation.
Ternary operator is supposed to return a single value, hence the single statement restriction. You are also not supposed to use functions with any significant side effects in ternary operator.
What you propose inevitably leads to very unreadable code, you should focus on readability, not number of lines/characters. Most code is read many more times that it is written/edited.
EDIT:
You can also use assert to similar ends.
assert($pMana > 20);
$pMana -= 20
However assertions should never be used to handle common situations (such as user input validation). The rule of thumb is that failed assertion should ALWAYS indicate a bug in your code. Assertion expressions should cover assumptions about input from other parts of the program/program state in the name of "Catch errors as soon as possible" motto (in this case it would be used to prevent bugs from causing mana to become negative, possibly causing isses later on).
The ternary operator is usually used to assign a value to a variable. The logic statement should be used with "if".
精彩评论