PHP - If/else、for、foreach、while - 没有花括号?

发布于 2024-12-24 01:47:20 字数 981 浏览 5 评论 0 原文

真正想知道但从未发现的事情是 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;

至少我再次省略了结束分号并且(如预期的那样)发生了解析错误。

所以我的大问题是:我什么时候可以省略花括号以及在哪个结构/循环/函数中?我知道我绝对可以在 ifelse 中做到这一点。但是 whileforforeach 又如何呢?

是的,我知道在没有大括号的情况下进行编码是不安全、不智能的,而且还有诸如 $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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

朮生 2024-12-31 01:47:20

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

if ($x) echo 'foo';

与 相同,

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

但请记住,

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

始终打印“bar”

在内部,情况正好相反:if 只会查看下一个表达式,但 PHP 会处理 中的所有内容>{} 作为单个“分组”表达式。

其他控制语句也相同(foreach 等)

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 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)

烟织青萝梦 2024-12-31 01:47:20

有些地方你可以,但你永远不应该。

显式总是比隐式更好。

谁知道什么时候您必须返回并修改旧代码。很容易错过这些东西,而且这样做也没有任何收获。

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.

飘逸的'云 2024-12-31 01:47:20

如果你里面只有一个参数,它会工作得很好!但如果你想省略大括号,你可以使用冒号和结尾。
例子:

if(a < 1 ) :
    echo "a is less than 1";
else :
    echo "a is greater than 1";
endif;

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;
‖放下 2024-12-31 01:47:20

正如所说,您不想学习速记,并且接受的答案提供了关于省略花括号的很好的例子,但有一些东西需要添加。正如您所看到的,在 if ($x) echo 'foo'; 的情况下省略花括号是可以的。代码没有任何问题,没有性能或其他问题,并且其他开发人员可以读取。并且示例还向您表明,如果您编写

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

而不是

if ($x)
    echo 'foo';

echo 'bar';

You 可能会遇到不需要的结果,其中打印 bar 而您不希望打印它,并且如果您的代码充满了此类语句,那么它将让你更难阅读自己的代码,更难让其他人阅读它。

我不想学习速记,我只是想了解何时何地可以省略大括号的条件。

这些事情密切相关,因此如果您真的想了解哪里可以省略大括号,那么您必须了解或至少了解简写,请阅读

  1. PHP 控制结构
  2. PHP一般三元条件运算符和表达式

所以我的大问题是:我什么时候可以省略花括号以及在哪个结构/循环/函数中?

然而,大括号不是必需的,为了可读性和可维护性,许多开发人员会认为不包含它们是不好的风格。前两个链接应该为您提供在可以省略大括号时做出自己的决定所需的信息。
例如,以下代码片段没有任何问题,它们都执行完全相同的操作。

带大括号

if (PHP_VERSION_ID < 70000)
{
    print "PHP >= 7.0 required yours is ";
    print phpversion();
    print "\n";
    exit(1);
}

与相同

if (PHP_VERSION_ID < 70000) :
    print "PHP >= 7.0 required yours is ";
    print phpversion();
    print "\n";
    exit(1);
endif;

或者你可以使用点运算符

if (PHP_VERSION_ID < 80000)
    (print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n") . exit(1);

并且你可以使用三元条件运算符,甚至省略if 除了省略大括号之外

(PHP_VERSION_ID > 70000) ?: (print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n") . exit(1);

由于我们只打印,我们可以缩短它并删除一些打印字符串函数,这些函数在这里代表多个不带大括号的语句中的函数

(PHP_VERSION_ID > 70000) ?: (print "PHP >= 7.0 required yours is " . phpversion() . "\n") . exit(1);

从 php 7 开始,我们可以使用 Null 合并运算符

(PHP_VERSION_ID > 70000) ?: null ?? (print "PHP >= 7.0 required yours is ".phpversion() . "\n") . exit(1);

正如我们所见,有多种方法可以获得完全相同的结果。这不仅适用于这个 if 示例,而且可以通过 struct/loop/function 进行实践。因此,您的大问题没有一个答案。主要应考虑以下几点。

  1. 您编写的代码是否易于维护。
  2. 你能自己回答一下,通过省略花括号你是否会赢得一些东西。

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

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.

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

  1. PHP Control Structures
  2. The PHP ternary conditional operators and expressions in general

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.

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

(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

(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_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.

  1. Is the code you are writing easy to maintain.
  2. Can you answer for your self is there something you win by omitting curly braces.
说谎友 2024-12-31 01:47:20

您可以将它用于简单的事情,例如:

if($a === true) continue;

但对于一些更复杂的子条件,它可能会给您带来问题:

    $a = false;
    $b = false;
    if ($a === true)
        if ($b === true)
            echo 1;
    else
        echo 2;

对于上面的代码,您希望看到“2”作为输出,但您不会。

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.

彻夜缠绵 2024-12-31 01:47:20

我在 PHP 模板中省略了大括号。例如,您可以按如下方式使用循环:

<ul>
    <?php foreach ($var as $value): ?>
        <li><?php echo $value; ?></li>
    <?php endforeach; ?>
</ul>

I omit curly braces in my PHP templates. E.g. you can use loops as follows:

<ul>
    <?php foreach ($var as $value): ?>
        <li><?php echo $value; ?></li>
    <?php endforeach; ?>
</ul>
つ低調成傷 2024-12-31 01:47:20

为了补充 @Marko 的答案,请注意,在使用点运算符时,您应该将每个操作括在括号内,否则顺序颠倒。

例如,下面的代码将打印 PHP >= 7.0 required yours is 5.6.15

(print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n");

虽然这将打印 5.6.151PHP >= 7.0 required yours is 1

print("PHP >= 7.0 required yours is ") . print(phpversion()) . print("\n");

您还可以使用 and 运算符来实现此目的。就像这样:

if (PHP_VERSION_ID < 70000)
    print("PHP >= 7.0 required yours is ") and
    print(phpversion()) and
    print("\n");

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.

(print "PHP >= 7.0 required yours is ") . (print phpversion()) . (print "\n");

While this will print 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:

if (PHP_VERSION_ID < 70000)
    print("PHP >= 7.0 required yours is ") and
    print(phpversion()) and
    print("\n");
美男兮 2024-12-31 01:47:20

对于单行语句。

如果您尝试这样做,

foreach($array as $x => $y)
    $do_something = $x;
    $do_something_else = $y;

除非我弄错了,否则 php 解释器会将 foreach 语句下的第二行视为隐含大括号之外,

因为如果您稍后返回此代码,或者其他开发人员查看了您的代码,则由于缩进工作的话会很混乱。

因此,在这些语句中始终使用大括号通常是明智的。它将避免以后的头痛/混乱

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

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

拥抱没勇气 2024-12-31 01:47:20

什么时候可以省略大括号以及在哪个结构/循环/函数中?
我知道我绝对可以在 if 和 else 中做到这一点。但是呢
while、for 和 foreach?

对于If/else,可以通过使用以下构造来拥有不带花括号的单个多个语句

<?php
  if ($x):
    echo 'foo';
    echo 'bar';
  else:
    echo 'nofoo';
    echo 'nobar';
  endif;
?>

这个答案

对于whileforforeach,仅允许使用不带大括号的单个语句

<?php
foreach($array as $x => $y)
    $do_something = $x;
?>

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?

For If/else it is possible to have single and multiple statements without curly braces by using the following construct:

<?php
  if ($x):
    echo 'foo';
    echo 'bar';
  else:
    echo 'nofoo';
    echo 'nobar';
  endif;
?>

As described in this answer

For while, for and foreach, only single statements are allowed without curly brackets

<?php
foreach($array as $x => $y)
    $do_something = $x;
?>
野稚 2024-12-31 01:47:20

当你的子句后面只有一个表达式时,有可能会发生这种情况,

例如,

foreach($var as $value)
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

是正确的,但

foreach($var as $value)
    $somevar = $var;
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

不是,并且 php 解释器会认为 if 语句在 foreach 之外

It's possible when you have only one expression after your clause/

For example,

foreach($var as $value)
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

is correct, but

foreach($var as $value)
    $somevar = $var;
    if(1 + 1 == 2) {
        $arr[] = $value;
    };

is not, and php interpreter will think that if statement is outside foreach

梦年海沫深 2024-12-31 01:47:20

答案很简单。这在C/C++中也是一样的。

if、if/else、if/else if/else 和循环 =>如果下一条语句是单行,则可以省略花括号。

例如:

for($i= 0; $i<=100; $i++)
{
    if($i % 7 == 0)
    {   
        echo $i . "<br>";
    }

}

也可以这样写:

for($i= 0; $i<=100; $i++) if($i % 7 == 0) echo $i . "<br>";

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:

for($i= 0; $i<=100; $i++)
{
    if($i % 7 == 0)
    {   
        echo $i . "<br>";
    }

}

It can also be written in this way:

for($i= 0; $i<=100; $i++) if($i % 7 == 0) echo $i . "<br>";
汹涌人海 2024-12-31 01:47:20

PHP 简写表达式自 PHP 5.3 起可用

$condition ? $value_if_true : $value_if_false

$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )

PHP shorthand expression was available since PHP 5.3

$condition ? $value_if_true : $value_if_false

$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )
攒一口袋星星 2024-12-31 01:47:20

某个时刻,如果下一条语句只有一行,我也省略了大括号。

当时我认为我的代码看起来很酷而且很时尚,我应该尽可能地节省代码行。

但我意识到,从长远来看,明确是更有帮助的,特别是在项目的可维护性方面。

此外,我们永远不应该为了微观性能而牺牲重要的东西。

enter image description here

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.

南巷近海 2024-12-31 01:47:20

当您在代码块内执行单个操作时,省略 {} 大括号是完全可以的,但如果您要在该块上执行两个或多个操作,则需要对它们使用 {} 大括号,否则您会得到一个错误。

// Single action
    if (true)
        return 'true';

// Compound
    if (true) {
        $value = true;
        return $value;
    }

在单个操作中,您可以省略 {} 大括号,因为您将直接返回值。

在复合操作中,您必须放置大括号,因为您将执行两件事:

  1. 将布尔值“true”分配给 $value
  2. 返回 $value

我希望这确实有意义。

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.

// Single action
    if (true)
        return 'true';

// Compound
    if (true) {
        $value = true;
        return $value;
    }

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:

  1. assign the boolean 'true' to the $value
  2. return that $value

I hope this does make sense.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文