问题
I've never been a fan of brackets in control structures and only today I realised how it only accepts one statement within a bracket less if condition, if I have more than one statement it will throw a syntax error. Is this how PHP works or can it be something wrong with my IDE?
Obviously the error is clear but I just want to make sure this is normal.
If you have any other any links to other alternate syntax let me know please.
Bellow is just something I pasted from a project am doing and example of the syntax error.
if($this->reel3 = 1)
parent::addCash($this->$bet*2);
print(parent::getCash()); // < Line throwing the syntax error
else
// TODO
EDIT (FURTHERMORE)
After looking at some of the answer and comments I was wondering how its done in a professional environment, I know this is more about taste but I want to know from the professional out there if the style of the syntax matters?
Would
if(condition)
{
//something
} else {
//something
}
be better than
if(condition):
//something
else:
//something
endif;
or any other way of writing the same piece of code?
回答1:
This is how php works. If you don't put brackets around your if statement only the next statement is in the if block all other follow up statements are outside of it. But since you have a else block after it you will get a error.
(BTW: You make an assignment in the if block, so this will be always true)
Look at these 2 examples:
if($this->reel3 = 1)
parent::addCash($this->$bet*2); //In the if statement
print(parent::getCash()); //Outside the if statement
else
Same as:
if($this->reel3 = 1) {
parent::addCash($this->$bet*2);
}
print(parent::getCash());
//^^^^^ I think here it's more clear to see that this will give you a error, since it's between the if and else block which is not allowed
else { }
For more information about the control structure if see the manual: http://php.net/manual/en/control-structures.if.php
回答2:
Take a look at the answer of this question:
PHP conditionals, brackets needed?
And yes, it is PHP, not your IDE!
回答3:
This is perfectly normal of all programming languages that use brackets rather than indentation to designate blocks of code. Without the brackets, there is no way for the interpreter to know which lines are part of the if block and which aren't. The one-line if-block is a convenient shortcut: if you don't include any brackets, PHP like many other languages will treat the single line directly following the if statement as the body of the if block.
Note PHP does have an alternative syntax for if statements as well, using colons instead of brackets, but that's a story for another day.
来源:https://stackoverflow.com/questions/28799434/php-bracket-less-if-condition-not-accepting-more-than-one-statement