我从来都不喜欢控制结构中的括号,直到今天我才意识到它只接受括号内的一个语句,如果条件不多,如果我有多个语句,它将抛出语法错误。这是 PHP 的工作方式还是我的 IDE 有问题?
显然错误很明显,但我只是想确保这是正常的。
如果您有其他替代语法的任何链接,请告诉我。
Bellow 只是我从一个正在做的项目中粘贴的内容和语法错误的示例。
if($this->reel3 = 1)
parent::addCash($this->$bet*2);
print(parent::getCash()); // < Line throwing the syntax error
else
// TODO
编辑(进一步)
在查看了一些答案和评论后,我想知道它在专业环境中是如何完成的,我知道这更多的是关于品味,但我想从专业人士那里了解语法风格是否重要?
会
if(condition)
{
//something
} else {
//something
}
优于
if(condition):
//something
else:
//something
endif;
或任何其他编写同一段代码的方式?
最佳答案
这就是 php 的工作原理。如果您不在 if 语句两边加上括号,则只有下一条语句在 if block 中,所有其他后续语句都在它之外。但是因为你在它后面有一个 else block ,你会得到一个错误。
(顺便说一句:您在 if block 中进行了赋值,因此这将始终为真)
看看这两个例子:
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
关于PHP 括号少 IF 条件不接受多个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799434/