php - 速记 switch 语句是否存在(在 PHP 中)?

标签 php switch-statement shorthand

我想将同一个变量(或表达式)与许多不同的值进行比较,并根据它等于哪个值返回不同的值。我想这样做 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条件
  • 每组条件都增加了一层额外的嵌套

我的问题:是否有一种方法允许我使用类似于开关的速记语法直接为变量赋值?

如果没有,我将有兴趣了解为什么存在该限制。

最佳答案

从 PHP 8.0 开始,有一个名为 ma​​tch 的速记开关可用

$colorType = match($color) {
    'red', 'blue' => handlePrimaryColor($in),
    'yellow', 'cyan' => handleSecondaryColor($in),
    'azure', 'violet' => handleTertiaryColor($in),
    default => null
};

关于php - 速记 switch 语句是否存在(在 PHP 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26062298/

相关文章:

java - 为什么算术赋值运算符更有效?

jquery find() 语句的简写

javascript - 创建一个遍历页面的查询字符串 HTML 表单?

php - 如何构造复杂的嵌套 SOAP 参数

c++ - switch case 中 map 迭代器的交叉初始化

jquery - 如何检测窗口大小,然后用 jquery switch 语句做一些事情

Python Match Case (Switch) 性能

通过悬停元素 B 对元素 A 的 CSS 转换

php - MYSQL在屏幕上分段打印日期

php - 将数据库中的用户计数到相同的用户级别