douduan5086 2013-03-28 13:14
浏览 422
已采纳

我可以在函数声明中省略花括号吗?

Currently, I'm declaring functions in PHP like:

function theFunction($theVar) {
   ...
}

And in JavaScript like:

function theFunction(theVar) {
   ...
}

Can I omit the curly braces when the function only contains one line? Like:

function theFunction($theVar)
   doSomething();

And:

function theFunction(theVar)
   doSomething();
  • 写回答

4条回答 默认 最新

  • drcrc28428 2013-03-28 13:20
    关注

    As far as I'm aware, that's not allowed by either language.

    They both allow it for single-statement if()s and loops, but not for functions (and in the case of PHP, not for classes either).

    But even if it was allowed, I'd strongly recommend against it; the braces are there for a reason, to aid readability and avoid ambiguity. I'd recommend always using them for if()s and loops for the same reason, even though they're not strictly required there.

    Languages like Python get away without braces because they have very strict indentation rules. Without those rules, a language need braces (or some other block marker); if you don't use them, you run a very high risk of your code having logic errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像