php - 在没有 else 条件的情况下结束 if...else 语句的最佳实践

标签 php coding-style if-statement

在没有 else 条件的情况下结束 if...else 语句的最佳做法是什么?考虑以下代码:

$direction = $_POST['direction']; //Up or down

if ($direction == "up") {
  code goes here...
}

elseif ($direction == "down") {
  code goes here...
}

else {
  //do nothing?
}

如您所见,只有两个条件; up 或 down,否则 else 语句实际上没有任何用处,除非您希望它显示错误消息。

大多数时候,我看到程序员只是将 else 条件放在那里,但会插入注释而不是像这样的任何工作代码。

else {
      //error messages goes here...
}

或者只是假设如果它不是“向上”,那么其他一切都应该是“向下”,因为只有 2 个条件。如果用户输入“左”或“右”,它仍将被视为“下”。我认为这有些不妥。

if ($direction == 'up') {
  code goes here...
}

else {
  code goes here...
}

我知道如果我们在没有 else 条件的情况下放置 if,PHP 仍然可以工作。但是如果有 elseif 条件呢?在这种情况下,如果我们不想包含任何错误消息或有任何其他条件,如果我们想保持严格的 if...else 语句,最佳做法是什么?

提前致谢。

最佳答案

没有if...else语句。
只有 if 语句可以使用 elseelseif 运算符进行扩展。

因此,不带 else 条件的 if 语句的最佳实践是不带 else 条件的 if 语句:

if (condition) {
  //some code
}

坦率地说,没有最佳实践。最好的做法就是遵循程序逻辑。
就这样

关于php - 在没有 else 条件的情况下结束 if...else 语句的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5313706/

相关文章:

php - 为什么这个恶意代码一直附加到我的 index.php 文件中?

php - 从 PHP 执行 Ruby 脚本并获取输出

linux - checkpatch.pl 标记八进制权限错误

php - unique_with laravel :It doesnt work if a particular row is ignored using id

php - 使用 JSON 发送和读取

python - Python 中首选 `if x:` 或 `if x != 0:` 中的哪一个?

objective-c - 在 Objective C 中,if (object == nil) 和 if (nil == object) 之间有区别吗?

c++ - IF 或 WHILE 用于数字输入检查器

android - "if"工作不正常

关于 css 高度的 JavaScript If Else 语句