【问题标题】:PHP Translating a ENUM in switch case not workingPHP在switch case中翻译ENUM不起作用
【发布时间】:2021-08-22 06:37:54
【问题描述】:
        echo $state;  //debug
        switch($state){
            case "Sleeping":
                $label = "Is Sleeping";
            case "Running":
                $label = "Is Running";
            default: 
                $label = "Could not retrieve state";
        }

$state 是从 SQL 数据库(Enum 类型)填充的,echo 消息打印“Sleeping”,但 $label 填充的是默认值

【问题讨论】:

  • 您需要在每种情况下都包含断句。执行从第一种情况“下降”到默认情况。 php.net/manual/en/control-structures.switch.php您已经在链接中详细解释了您的代码中发生的事情。
  • 对,菜鸟的错误。我通常知道这一点.. :o

标签: php enums switch-statement


【解决方案1】:

PHP switch 语句在找到匹配项后继续执行 switch 块的剩余部分,直到找到 break; 语句。您需要在每个案例的末尾添加break;

        echo $state;  //debug
        switch($state){
            case "Sleeping":
                $label = "Is Sleeping";
                break;
            case "Running":
                $label = "Is Running";
                break;
            default: 
                $label = "Could not retrieve state";
        }

【讨论】:

    【解决方案2】:

    在您的情况下,选择 match (PHP 8) 表达式明显更短,并且不需要 break 语句。

    $state = "Running";
    $label = match ($state) {
        "Sleeping"=> "Is Sleeping",
        "Running" => "Is Running",
        default => "Could not retrieve state"
    };
    echo $label; // "Is Running"
    

    【讨论】:

    • 附带说明这是 PHP 8 的功能。
    • 是的,我添加了对它的引用!
    【解决方案3】:

    为了完整性:

    $states = [
        'Sleeping' => 'Is Sleeping',
        'Running' => 'Is Running',
    ];
    echo $states[$state] ?? 'Could not retrieve state';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多