【发布时间】:2014-11-21 15:02:08
【问题描述】:
我想将同一个变量(或表达式)与许多不同的值进行比较,并根据它等于哪个值返回不同的值。我想这样做inline or shorthand,就像使用if 语句一样。
采取以下switch 声明:
switch($color_name) {
case 'red':
case 'blue':
$color_type = handlePrimaryColor($in);
break;
case 'yellow':
case 'cyan':
$color_type = handleSecondaryColor($in);
break;
case 'azure':
case 'violet':
$color_type = handleTertiaryColor($in);
break;
default:
$color_type = null;
break;
}
我不喜欢在任何情况下都写$color_type =,我想找到一种方法来用更少的代码做到这一点。
我可以用某种形式的速记语法来做到这一点。下面,我使用shorthand if statement 为变量在首次声明的同一位置赋值:
$color_type = $color_name == 'red' || $color_name == 'blue'
? handlePrimaryColor($color_name)
: ($color_name == 'yellow' || $color_name == 'cyan'
? handleSecondaryColor($color_name)
: ($color_name == 'azure' || $color_name == 'violet'
? handleTertiaryColor($color_name)
: null
)
);
这种方法不需要在每个构造中声明变量,而是给我带来了两个新问题:
- 我现在必须为每种颜色编写一个新的
OR条件 - 每组条件都会增加一层嵌套
我的问题:有没有一种方法可以让我使用类似于开关的速记语法直接为变量赋值?
如果没有,我有兴趣了解为什么存在这种限制。
【问题讨论】:
-
我打赌你的同事都爱你
-
这是为什么呢?我只是想了解是否可以将我的 switch 语句翻译成简写版本。实际上,我不会让我的同事接触多层嵌套的内联 if 语句。我的代码在问题中的主题和内容仅作为示例。
-
这只是一个轻松的评论 - 我以前在野外遇到过这样的代码,这是一次令人沮丧的经历!
-
嘿,轻描淡写,我只是担心有人会认为我生成了这样的代码,而我的问题的目的是避免它:)
标签: php switch-statement shorthand