3

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?

4

3 回答 3

3

这就是 php 的工作原理。如果你没有在你的 if 语句周围加上括号,那么只有下一个语句在 if 块中,所有其他后续语句都在它之外。但是由于你后面有一个 else 块,你会得到一个错误。

(顺便说一句:您在 if 块中进行了分配,所以这将始终是正确的)

看看这两个例子:

if($this->reel3 = 1)
   parent::addCash($this->$bet*2); //In the if statement
   print(parent::getCash());  //Outside the if statement
else

如同:

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 { }

有关控制结构的更多信息,请参阅手册: http: //php.net/manual/en/control-structures.if.php

于 2015-03-01T21:43:56.513 回答
2

看看这个问题的答案:

PHP条件,需要括号?

是的,它是 PHP,而不是你的 IDE!

于 2015-03-01T21:41:20.900 回答
2

这对于所有使用括号而不是缩进来指定代码块的编程语言来说是完全正常的。如果没有括号,解释器就无法知道哪些行是 if 块的一部分,哪些不是。单行 if 块是一种方便的快捷方式:如果不包含任何括号,PHP 像许多其他语言一样会将 if 语句后面的单行视为 if 块的主体。

注意 PHP 也有 if 语句的替代语法,使用冒号而不是括号,但这是另一天的故事。

于 2015-03-01T21:43:47.887 回答