PHP - If/else, for, foreach, while - 没有花括号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8726339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - If/else, for, foreach, while - without curly braces?
提问by headacheCoder
Something that really would like to know but never found out are shortcuts in PHP.
一些真正想知道但从未发现的东西是 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
循环的函数,里面只有一个语句。我试图省略花括号,就像你在 if/else 控制结构中所做的那样,它可以工作。没有错误。
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.
现在我尝试以相同的方式使用它,但在其中放置了一个 if/else 块。再次,工作,没有错误。
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 循环中再次使用不带花括号的 if/else 语句,仍然有效且没有错误。但是 foreach 循环现在真的关闭/结束了吗?
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
?
所以我的大问题是:我什么时候可以省略花括号以及在哪个结构/循环/函数中?我知道我绝对可以在if
和 中这样做else
。但是while
,for
和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.
是的,我知道它不安全,不聪明,无论编码没有花括号,还有像$condition ? true : false;
and if: doSomething(); endif;
、endfor;
and这样的速记endforeach;
。我不想了解速记,我只想了解有关何时何地可以省略大括号的条件。
回答by KingCrunch
When you omit the braces it will only treat the next statement as body of the condition.
当您省略大括号时,它只会将下一个语句视为条件的主体。
if ($x) echo 'foo';
is the same as
是相同的
if ($x) { echo 'foo'; }
but remember that
但请记住
if ($x)
echo 'foo';
echo 'bar';
will alwaysprint "bar"
将始终打印“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.
在内部,情况正好相反:if
只会查看下一个表达式,但 PHP 将其中的所有内容{}
视为单个“分组”表达式。
Same for the other control statements (foreach
, and so on)
其他控制语句(foreach
,等等)
回答by tkone
There are places where you can, but you never should.
有些地方你可以,但你永远不应该。
Explicit is alwaysbetter 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.
谁知道你什么时候必须回去修改旧代码。很容易错过那些东西,而这样做并没有任何好处。
回答by site stats
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(a < 1 ) :
echo "a is less than 1";
else :
echo "a is greater than 1";
endif;
回答by mkungla
As have said you don't wanna learn about shorthand'sand accepted answer gives good example about omitting curly braces
, but there is something to add. As you can see it's fine to omit curly braces
in case of if ($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 write
如前所述,您不想了解速记,接受的答案提供了关于省略的很好的例子curly braces
,但还有一些要补充的。如您所见,curly braces
在if ($x) echo 'foo';
. 代码没有问题,没有性能或其他问题,其他开发人员可以阅读。并且示例还向您表明,如果您写
if ($x)
echo 'foo';
echo 'bar';
instead of
代替
if ($x)
echo 'foo';
echo 'bar';
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.
您可能会在不希望bar
打印的情况下在打印的地方遇到不需要的结果,如果您的代码中充满了此类语句,那么您将更难阅读自己的代码,而其他人则更难阅读它.
I don't wanna learn about shorthand's I just want to understand the conditions about when and where it is possible to omit the curly brackets.
我不想了解速记,我只想了解有关何时何地可以省略大括号的条件。
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
这些东西是密切相关的,所以如果你真的想了解可以省略大括号的地方,那么这应该是你理解或至少知道速记的必须,已经阅读
So my big question is: When can I omit the curly braces and in which structure/loop/function?
所以我的大问题是:我什么时候可以省略花括号以及在哪个结构/循环/函数中?
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.
大括号不是必需的,但是为了可读性和维护,许多开发人员会认为不包含它们是不好的风格。当您可以省略花括号时,前 2 个链接应该为您提供做出自己决定所需的信息。例如,以下代码片段没有任何问题,它们都做完全相同的事情。
With curly brace
带花括号
if (PHP_VERSION_ID < 70000)
{
print "PHP >= 7.0 required yours is ";
print phpversion();
print "\n";
exit(1);
}
Is same as
是一样的
if (PHP_VERSION_ID < 70000) :
print "PHP >= 7.0 required yours is ";
print phpversion();
print "\n";
exit(1);
endif;
Or you can use the dot operator
或者您可以使用点运算符
if (PHP_VERSION_ID < 80000)
(print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n") . exit(1);
And you can make use of the ternary conditional operator and even omit if
it self besides omitting curly braces
您可以使用三元条件运算符,甚至if
除了省略花括号之外,还可以省略它自己
(PHP_VERSION_ID > 70000) ?: (print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n") . exit(1);
Since 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 braces
由于我们只打印,我们可以缩短它并去掉一些print string functions
在没有花括号的语句中表示多个函数的地方
(PHP_VERSION_ID > 70000) ?: (print "PHP >= 7.0 required yours is " . phpversion() . "\n") . exit(1);
As from php 7 we can use Null coalescing operator
从 php 7 开始,我们可以使用 Null 合并运算符
(PHP_VERSION_ID > 70000) ?: null ?? (print "PHP >= 7.0 required yours is ".phpversion() . "\n") . exit(1);
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 with structure/loop/function
. So there is no one answer for your big question. One should consider mainly following.
正如人们所见,您可以通过多种方式获得完全相同的结果。这不仅适用于这个if
例子,而且同样可以用structure/loop/function
. 所以你的大问题没有一个答案。主要应该考虑以下几点。
- Is the code you are writing easy to maintain.
- Can you answer for your self is there something you win by omitting curly braces.
- 您正在编写的代码是否易于维护。
- 你能回答你自己是否通过省略花括号来赢得一些东西。
回答by Georg Leber
I omit curly braces in my PHP templates. E.g. you can use loops as follows:
我在 PHP 模板中省略了花括号。例如,您可以按如下方式使用循环:
<ul>
<?php foreach ($var as $value): ?>
<li><?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
回答by Iliya Kolev
You can use it for simple things like:
您可以将它用于简单的事情,例如:
if($a === true) continue;
But for some more complicated sub-conditions it may cause you problems:
但是对于一些更复杂的子条件,它可能会给您带来问题:
$a = false;
$b = false;
if ($a === true)
if ($b === true)
echo 1;
else
echo 2;
With the code above, you would expect to see "2" as output, but you won't.
使用上面的代码,您希望看到“2”作为输出,但实际上不会。
回答by Pete Mitchell
For single line statements.
对于单行语句。
If you tried to do
如果你试图做
foreach($array as $x => $y)
$do_something = $x;
$do_something_else = $y;
Unless I am mistaken the php interpreter will take the second line under the foreach statement as being outside of the implied braces
除非我弄错了,否则 php 解释器会将 foreach 语句下的第二行视为隐含的大括号之外
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
因此,在这些语句中始终使用大括号通常是明智的。它将避免以后的头痛/困惑
回答by Renan Decarlo
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.
为了补充@Marko的回答,请注意,在针对此问题使用点运算符时,应将每个操作括在括号中,否则会颠倒顺序。
For instance, this code below will print PHP >= 7.0 required yours is 5.6.15
.
例如,下面的代码将打印PHP >= 7.0 required yours is 5.6.15
.
(print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n");
While this will print 5.6.151PHP >= 7.0 required yours is 1
.
虽然这将打印5.6.151PHP >= 7.0 required yours is 1
.
print("PHP >= 7.0 required yours is ") . print(phpversion()) . print("\n");
You can also use the and
operator for this to work. Like so:
您也可以使用and
运算符来实现这一点。像这样:
if (PHP_VERSION_ID < 70000)
print("PHP >= 7.0 required yours is ") and
print(phpversion()) and
print("\n");
回答by Duffmannen
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?
我什么时候可以省略花括号以及在哪个结构/循环/函数中?我知道我绝对可以在 if 和 else 中这样做。但是,while、for 和 foreach 呢?
For If/elseit is possible to have singleand multiple statementswithout curly braces by using the following construct:
对于If/else,通过使用以下结构可以有一个和多个没有花括号的语句:
<?php
if ($x):
echo 'foo';
echo 'bar';
else:
echo 'nofoo';
echo 'nobar';
endif;
?>
As described in this answer
For while, forand foreach, only single statementsare allowed without curly brackets
对于while、for和foreach,只允许没有大括号的单个语句
<?php
foreach($array as $x => $y)
$do_something = $x;
?>
回答by Midhun1993
PHP shorthand expression was available since PHP 5.3
PHP 速记表达式从 PHP 5.3 开始可用
$condition ? $value_if_true : $value_if_false
$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )