PHP 在 switch case 中转换 ENUM 不起作用
PHP Translating a ENUM in switch case not working
echo $state; //debug
switch($state){
case "Sleeping":
$label = "Is Sleeping";
case "Running":
$label = "Is Running";
default:
$label = "Could not retrieve state";
}
$state 由 SQL 数据库(枚举类型)填充,回显消息打印“Sleeping”,但 $label 填充的是默认值
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";
}
在您的情况下,选择 match
(PHP 8) 表达式明显更短,并且不需要 break
语句。
$state = "Running";
$label = match ($state) {
"Sleeping"=> "Is Sleeping",
"Running" => "Is Running",
default => "Could not retrieve state"
};
echo $label; // "Is Running"
完整性:
$states = [
'Sleeping' => 'Is Sleeping',
'Running' => 'Is Running',
];
echo $states[$state] ?? 'Could not retrieve state';
echo $state; //debug
switch($state){
case "Sleeping":
$label = "Is Sleeping";
case "Running":
$label = "Is Running";
default:
$label = "Could not retrieve state";
}
$state 由 SQL 数据库(枚举类型)填充,回显消息打印“Sleeping”,但 $label 填充的是默认值
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";
}
在您的情况下,选择 match
(PHP 8) 表达式明显更短,并且不需要 break
语句。
$state = "Running";
$label = match ($state) {
"Sleeping"=> "Is Sleeping",
"Running" => "Is Running",
default => "Could not retrieve state"
};
echo $label; // "Is Running"
完整性:
$states = [
'Sleeping' => 'Is Sleeping',
'Running' => 'Is Running',
];
echo $states[$state] ?? 'Could not retrieve state';