真正想知道但从未发现的事情是 PHP 中的快捷方式。
我目前正在编写一个带有 foreach
循环的函数,其中只有一条语句。我尝试省略大括号,就像在 if/else 控制结构中所做的那样,并且它有效。没有错误。
foreach($var as $value)
$arr[] = $value;
现在我尝试以相同的方式使用它,但在其中放入 if/else 块。再次,工作正常,没有错误。
foreach($var as $value)
if(1 + 1 == 2) {
$arr[] = $value;
};
然后,我想“为什么这有效?”并省略了结束分号。还在工作。因此,我尝试在 foreach 循环内使用不带大括号的 if/else 语句,并且仍然有效并且没有错误。但是 foreach 循环现在真的关闭/结束了吗?
foreach($var as $value)
if(1 + 1 == 2)
$arr[] = $value;
至少我再次省略了结束分号并且(如预期的那样)发生了解析错误。
所以我的大问题是:我什么时候可以省略花括号以及在哪个结构/循环/函数中?我知道我绝对可以在 if
和 else
中做到这一点。但是 while
、for
和 foreach
又如何呢?
是的,我知道在没有大括号的情况下进行编码是不安全、不智能的,而且还有诸如 $condition 之类的简写? true : false;
和 if: doSomething(); endif;
、endfor;
和 endforeach;
。我不想学习速记,我只想了解何时何地可以省略大括号的条件。
Something that really would like to know but never found out are shortcuts in PHP.
I am currently coding a function with a foreach
loop with just a single statement inside. I tried to omit the curly braces as you can do in if/else control structures and it works. No errors.
foreach($var as $value)
$arr[] = $value;
Now I tried to use it the same way but putting an if/else block inside it. Again, working and no errors.
foreach($var as $value)
if(1 + 1 == 2) {
$arr[] = $value;
};
Then, I thought like "why is this working?" and omitted the closing semicolon. Still working. So I tried to use the if/else statement without curly braces inside the foreach loop and again, still working and no errors. But is the foreach loop really closed/ended right now?
foreach($var as $value)
if(1 + 1 == 2)
$arr[] = $value;
At least I omitted the closing semicolon again and (as expected) a parsing error occurred.
So my big question is: When can I omit the curly braces and in which structure/loop/function? I know that I can definitely do so in if
and else
. But what about while
, for
and foreach
?
And yes, I know that it is not safe, smart, whatever to code without curly braces and there are shorthands like $condition ? true : false;
and if: doSomething(); endif;
, endfor;
and endforeach;
. I don't wanna learn about shorthands I just want to understand the conditions about when and where it is possible to omit the curly brackets.
发布评论
评论(14)
当您省略大括号时,它只会将下一个语句视为条件主体。
与 相同,
但请记住,
将始终打印“bar”
在内部,情况正好相反:
if
只会查看下一个表达式,但 PHP 会处理中的所有内容>{}
作为单个“分组”表达式。其他控制语句也相同(
foreach
等)When you omit the braces it will only treat the next statement as body of the condition.
is the same as
but remember that
will always print "bar"
Internally it's the other way around:
if
will only look at the next expression, but PHP treats everything in{}
as a single "grouped" expression.Same for the other control statements (
foreach
, and so on)有些地方你可以,但你永远不应该。
显式总是比隐式更好。
谁知道什么时候您必须返回并修改旧代码。很容易错过这些东西,而且这样做也没有任何收获。
There are places where you can, but you never should.
Explicit is always better than implicit.
Who knows when you're going to have to go back and modify old code. It's so easy to miss that stuff and there's nothing gained by doing it.
如果你里面只有一个参数,它会工作得很好!但如果你想省略大括号,你可以使用冒号和结尾。
例子:
It will work fine if you only have one argument inside!. But if you want to omit curly brace you can use colon and end.
example:
正如所说,您不想学习速记,并且接受的答案提供了关于省略
花括号
的很好的例子,但有一些东西需要添加。正如您所看到的,在if ($x) echo 'foo';
的情况下省略花括号
是可以的。代码没有任何问题,没有性能或其他问题,并且其他开发人员可以读取。并且示例还向您表明,如果您编写而不是
You 可能会遇到不需要的结果,其中打印
bar
而您不希望打印它,并且如果您的代码充满了此类语句,那么它将让你更难阅读自己的代码,更难让其他人阅读它。这些事情密切相关,因此如果您真的想了解哪里可以省略大括号,那么您必须了解或至少了解简写,请阅读
然而,大括号不是必需的,为了可读性和可维护性,许多开发人员会认为不包含它们是不好的风格。前两个链接应该为您提供在可以省略大括号时做出自己的决定所需的信息。
例如,以下代码片段没有任何问题,它们都执行完全相同的操作。
带大括号
与相同
或者你可以使用点运算符
并且你可以使用三元条件运算符,甚至省略
if
除了省略大括号之外由于我们只打印,我们可以缩短它并删除一些
打印字符串函数
,这些函数在这里代表多个不带大括号的语句中的函数从 php 7 开始,我们可以使用 Null 合并运算符
正如我们所见,有多种方法可以获得完全相同的结果。这不仅适用于这个
if
示例,而且可以通过struct/loop/function
进行实践。因此,您的大问题没有一个答案。主要应考虑以下几点。As have said you don't wanna learn about shorthand's and accepted answer gives good example about omitting
curly braces
, but there is something to add. As you can see it's fine to omitcurly braces
in case ofif ($x) echo 'foo';
. There is nothing wrong with code, no performance or other issues and it is readable by other developers. And example also shows you that if you writeinstead of
You can run into unwanted results where
bar
is printed while you don't want it to be printed and if your code is full of such statements then it will make it harder for you to read your own code and even more harder for others to read it.These things are closely related so if you really want to understand where it is possible to omit curly brackets then that should be a must that you understand or are at least aware of shorthand's , have read
The curly brace is not required however, for readability and maintenance, many developers would consider it bad style not to include them. Previous 2 links should give you information needed to make your own decisions when you could omit curly brace.
for example there is nothing wrong with following code snippets which all do exactly same thing.
With curly brace
Is same as
Or you can use the dot operator
And you can make use of the ternary conditional operator and even omit
if
it self besides omitting curly bracesSince we only print we can shorten that and strip some
print string functions
which were here to represent more than one function in statement without curly bracesAs from php 7 we can use Null coalescing operator
As one can see that there is many ways you can get exactly the same result. That not only applies for this
if
example but same can be practiced withstructure/loop/function
. So there is no one answer for your big question. One should consider mainly following.您可以将它用于简单的事情,例如:
但对于一些更复杂的子条件,它可能会给您带来问题:
对于上面的代码,您希望看到“2”作为输出,但您不会。
You can use it for simple things like:
But for some more complicated sub-conditions it may cause you problems:
With the code above, you would expect to see "2" as output, but you won't.
我在 PHP 模板中省略了大括号。例如,您可以按如下方式使用循环:
I omit curly braces in my PHP templates. E.g. you can use loops as follows:
为了补充 @Marko 的答案,请注意,在使用点运算符时,您应该将每个操作括在括号内,否则顺序颠倒。
例如,下面的代码将打印
PHP >= 7.0 required yours is 5.6.15
。虽然这将打印
5.6.151PHP >= 7.0 required yours is 1
。您还可以使用
and
运算符来实现此目的。就像这样:To complement @Marko's answer, be aware that when using the dot operator for this matter, you should enclose each operation in parentheses, otherwise it will reverse the order.
For instance, this code below will print
PHP >= 7.0 required yours is 5.6.15
.While this will print
5.6.151PHP >= 7.0 required yours is 1
.You can also use the
and
operator for this to work. Like so:对于单行语句。
如果您尝试这样做,
除非我弄错了,否则 php 解释器会将 foreach 语句下的第二行视为隐含大括号之外,
因为如果您稍后返回此代码,或者其他开发人员查看了您的代码,则由于缩进工作的话会很混乱。
因此,在这些语句中始终使用大括号通常是明智的。它将避免以后的头痛/混乱
For single line statements.
If you tried to do
Unless I am mistaken the php interpreter will take the second line under the foreach statement as being outside of the implied braces
Due to the indentation if you came back to this code at a later date, or another developer looked at your work it would be confusing.
As such it is generally wise to always use braces with these statements. It will save later headache/confusion
对于If/else,可以通过使用以下构造来拥有不带花括号的单个和多个语句:
如这个答案
对于while、for 和 foreach,仅允许使用不带大括号的单个语句
For If/else it is possible to have single and multiple statements without curly braces by using the following construct:
As described in this answer
For while, for and foreach, only single statements are allowed without curly brackets
当你的子句后面只有一个表达式时,有可能会发生这种情况,
例如,
是正确的,但
不是,并且 php 解释器会认为
if
语句在foreach
之外It's possible when you have only one expression after your clause/
For example,
is correct, but
is not, and php interpreter will think that
if
statement is outsideforeach
答案很简单。这在C/C++中也是一样的。
if、if/else、if/else if/else 和循环 =>如果下一条语句是单行,则可以省略花括号。
例如:
也可以这样写:
The answer is easy. This is the same in C/C++.
if, if/else, if/else if/ else and loops => If the next statement is one single line, you can omit the curly braces.
Ex:
It can also be written in this way:
PHP 简写表达式自 PHP 5.3 起可用
PHP shorthand expression was available since PHP 5.3
某个时刻,如果下一条语句只有一行,我也省略了大括号。
当时我认为我的代码看起来很酷而且很时尚,我应该尽可能地节省代码行。
但我意识到,从长远来看,明确是更有帮助的,特别是在项目的可维护性方面。
此外,我们永远不应该为了微观性能而牺牲重要的东西。
At one point in my life, I also ommitted the curly braces if the next statement only have one line.
Back then I thought that my code looks cool and sleek and that I should save line of codes as much as possible.
But I realized that being explicit is more helpful in the long run, especially in regards to maintainability of the project.
Also, we should never sacrifice significant things over microperformance.
当您在代码块内执行单个操作时,省略 {} 大括号是完全可以的,但如果您要在该块上执行两个或多个操作,则需要对它们使用 {} 大括号,否则您会得到一个错误。
在单个操作中,您可以省略 {} 大括号,因为您将直接返回值。
在复合操作中,您必须放置大括号,因为您将执行两件事:
我希望这确实有意义。
It's perfectly fine to omit the {} curly braces when you perform single action inside the code block, but if you will execute two or more actions on that block, then you will need to use the {} curly braces for them, or else you will get an error.
In single action, you can omit the {} braces because you will return the value directly.
In compound action, you have to put the braces because you will perform two things:
I hope this does make sense.