PHP简写if / else if - Basic

时间:2011-03-17 21:01:30

标签: php shorthand

我有一段现有的代码,我在理解方面遇到了问题。

我通常不喜欢速记,因为它需要配置更改,而且我更难阅读。出于这个原因,我并不是特别熟悉它。现有的代码是由喜欢速记的人写的。

当我遇到这个时:

if($type == 'a') $type = 'Type A';
else if($type == 'b') $type = 'Type B';
else if($type == 'c') $type = 'Type C';

我把它读作简单的if,而不是if字符串。我将其转换为:

if($type == 'a') {
  $type = 'Type A';
} else if($type == 'b') {
  $type = 'Type B';
} else if($type == 'c') {
  $type = 'Type C';
}

我认为这很简单,但是我在实践中得到了不同的结果。上面两个片段有什么区别?

6 个答案:

答案 0 :(得分:4)

它们完全相同,区别在于其他地方。

这是前后代码的复制/粘贴吗?

我同意anubhava,但为了清楚起见,我倾向于将其转换为开关案例:

switch ($type) {
  case 'a':
    $type = 'Type A';
    break;

  case 'b':
    $type = 'Type B';
    break;

  case 'c':
    $type = 'Type C';
    break;

  default:
    break;
}

答案 1 :(得分:1)

它们应该完全相同。我会制作一个测试文件,但我不认为这会改变这个事实......

哇,做了一个测试文件:

<?php
$type = 'a';

if($type == 'a') $type = 'Type A';
else if($type == 'b') $type = 'Type B';
else if($type == 'c') $type = 'Type C';
echo $type . "\n";


$type = 'b';

if($type == 'a') $type = 'Type A';
else if($type == 'b') $type = 'Type B';
else if($type == 'c') $type = 'Type C';
echo $type . "\n";


$type = 'c';

if($type == 'a') $type = 'Type A';
else if($type == 'b') $type = 'Type B';
else if($type == 'c') $type = 'Type C';
echo $type . "\n";


$type = 'a';

if($type == 'a') {
  $type = 'Type A';
} else if($type == 'b') {
  $type = 'Type B';
} else if($type == 'c') {
  $type = 'Type C';
}
echo $type . "\n";

$type = 'b';

if($type == 'a') {
  $type = 'Type A';
} else if($type == 'b') {
  $type = 'Type B';
} else if($type == 'c') {
  $type = 'Type C';
}

echo $type . "\n";
$type = 'c';

if($type == 'a') {
  $type = 'Type A';
} else if($type == 'b') {
  $type = 'Type B';
} else if($type == 'c') {
  $type = 'Type C';
}
echo $type . "\n";

,结果确实相同。

Type A
Type B
Type C
Type A
Type B
Type C

答案 2 :(得分:1)

我认为您首先需要php switch case来简化上述代码。

虽然我必须提到我没有找到任何代码差异2个版本的代码。切换案例使得它比许多if语句更具可读性,否则if,else if语句。

答案 3 :(得分:1)

这实际上不是shorthand语法。这只是一个if / else if / else,如果每个部分只有一个语句,因此不需要{}集。

使用换行符格式化时更清晰一点:

if($type == 'a')
    $type = 'Type A';
else if($type == 'b')
    $type = 'Type B';
else if($type == 'c')
    $type = 'Type C';

答案 4 :(得分:1)

是$ type返回一个不受欢迎的?如果是的话,我会:

if($type == 'a') {
  $type = 'Type A';
} else if($type == 'b') {
  $type = 'Type B';
} else if($type == 'c') {
  $type = 'Type C';
} else {
 $type = 'Other Type';
}

但我完全赞同上述人员,实际上你应该把它翻译为:

switch ($type) {
  case 'a':
    $type = 'Type A';
    break;

  case 'b':
    $type = 'Type B';
    break;

  case 'c':
    $type = 'Type C';
    break;

  default:
    $type = 'Other Type';
    break;
}

这样你就可以随时查看不需要的数据,具体取决于我总是设置默认设置的情况,尤其是开发模式。

答案 5 :(得分:0)

它们是相同的,错误在其他地方。

相关问题