是“elseif"吗?和“否则如果"完全同义?

2022-01-20 00:00:00 syntax conditional-statements php

elseifelse if 完全是同义词,还是有区别?

Are elseif and else if completely synonymous, or is there a difference?

Zend 有公认的标准"吗?

Does Zend have an accepted "standard" on which one to use?

虽然我个人不喜欢在代码中看到 elseif,但我只需要知道它们是否是同义词,而且 PHP 手册不是最容易搜索的.

While I personally dislike seeing elseif in the code, I just need to know if they're synonymous and the PHP manual isn't the easiest to search.

推荐答案

来自 PHP手册:

在 PHP 中,您还可以编写else if"(用两个词),其行为与elseif"(用一个词)的行为相同.语法含义略有不同(如果您熟悉 C,这是相同的行为),但底线是两者都会导致完全相同的行为.

In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

本质上,它们的行为是相同的,但是 else if 在技术上等同于这样的嵌套结构:

Essentially, they will behave the same, but else if is technically equivalent to a nested structure like so:

if (first_condition)
{

}
else
{
  if (second_condition)
  {

  }
}

手册还注明:

请注意,elseif 和 else if 只有在使用大括号时才会被视为完全相同,如上例所示.当使用冒号定义 if/elseif 条件时,不能将 else if 分成两个单词,否则 PHP 将失败并出现解析错误.

Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

这意味着在正常的控制结构形式中(即使用大括号):

Which means that in the normal control structure form (ie. using braces):

if (first_condition)
{

}
elseif (second_condition)
{

}

可以使用 elseifelse if.但是,如果您使用 替代语法,则必须使用 elseif:

either elseif or else if can be used. However, if you use the alternate syntax, you must use elseif:

if (first_condition):
  // ...
elseif (second_condition):
  // ...
endif;

相关文章