PHP - if / else,for,foreach,while - 没有花括号? [英] PHP - If/else, for, foreach, while - without curly braces?

查看:438
本文介绍了PHP - if / else,for,foreach,while - 没有花括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真正想知道但却从未发现的东西是PHP中的快捷方式。

Something that really would like to know but never found out are shortcuts in PHP.

我目前正在编写一个带有 foreach <的函数/ code>循环只包含一个语句。我试图省略花括号,因为你可以在if / else控制结构中做它并且它可以工作。没有错误。

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;

现在我尝试以相同的方式使用它,但在其中放入一个if / else块。再次,工作,没有错误。

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

然后,我想为什么这有效?并省略了结束分号。还在工作。所以我尝试在foreach循环中使用if / else语句而没有花括号,并再次使用,仍然正常,没有错误。但foreach循环现在是否真正关闭/结束?

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.

所以我的大问题是:我什么时候可以省略花括号和结构/循环/函数?我知道我肯定可以在中执行此操作,如果其他。但是时的 foreach

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?

是的,我知道它不安全,聪明,没有花括号的代码,还有像 $ condition这样的短序? true:false; if:doSomething(); endif; endfor; endforeach; 。我不想了解shorthands我只想了解有关何时何地可以省略大括号的条件。

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.

推荐答案

当你省略大括号时,它只会将下一个语句视为条件的主体。

When you omit the braces it will only treat the next statement as body of the condition.

if ($x) echo 'foo';

if ($x) { echo 'foo'; }

但请记住

if ($x)
  echo 'foo';
  echo 'bar';

始终打印bar

在内部它是相反的:如果只会查看下一个表达式,但PHP会处理 {}中的所有内容/ code>作为单个分组表达式。

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.

其他控制语句相同( foreach ,依此类推)

Same for the other control statements (foreach, and so on)

这篇关于PHP - if / else,for,foreach,while - 没有花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆