块-大括号/没有大括号? [英] Blocks - curly braces/no curly braces?

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

问题描述

当我开始开发时,我遵循了始终使用{}(大括号)包围块的教程.但是,当我开始查看其他人的代码时(例如GitHub上的类,或者比基本教程显示的代码更多),但是例如,我也看到了不包含在{}中的语句块;

When I started developing, I followed tutorials that always used {} (curly braces) to enclose blocks. However, when I began looking at other peoples code (classes on GitHub for example, or just more code in general than what a basic tutorial would show), however I've also seen block statements without being enclosed in {}, for example;

if($var < 15)
     $string = 'Hello, Jimmy!';
elseif($var >= 15)
     $string = 'Hello, Anne!';

if($var < 15) { 
    $string = 'Hello, Jimmy!';
} elseif($var >= 15) {
    $string = 'Hello, Anne!';
}

我从来没有使用过未包含在{}中的块,但是我今天使用了它们,并且开始看到这样做的效率(它看起来也很干净,因为我经常会发现我的函数很混乱从循环,条件等中使用{}

I've never used blocks not enclosed in {}, however I used them today and I'm starting to see the efficiency of doing so (it looks a lot cleaner too, as I'll often find my functions riddled with {} from loops, conditionals etc.

我要问的是;

a)对没有大括号的块有任何限制(;我注意到我输入一行后在if()有条件后返回,所以我的IDE从缩进回退了吗?

a) are there any limitations on blocks without curly braces (; I noticed my IDE dropped back from an indent after I enter a single line and returned after an if() conditional?

b)不使用{}时是否有最佳实践?

b) are there any best practices to be had, when not using {}?

任何答案,特别是那些公司.背景/文档中关于块大括号使用与不使用大括号的约定将不胜感激,因为我真的很想了解大括号的用法:)!

Any answers, specifically those inc. background/docs on the convention of curly brace usage for blocks vs. not using them would be greatly appreciated, as I'd really like to understand the usage of curly braces :)!

推荐答案

您可以为一行省略{}:

if(something)
  do something else

但是您不能忽略它,并且让它继续这样运行:

however you cannot omit it and have it keep going like so:

if(something)
   do one thing
   do another
   do some more

以上示例仅包含1个条件元素(做一件事").其余的将无条件运行.

The example above would only have 1 conditional element (the 'do one thing'). The rest would just run unconditionally.

是的,在没有{}的情况下,我见过草率的方法,我自己更喜欢使用{}来分隔逻辑,并且更易于阅读.

And yes I've seen the sloppy method before without the {}, I myself prefer using {} to separate the logic, and its easier to read.

因此请坚持在代码中使用{}.

So stick to using {} in your code.

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

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