PHP 枚举(Enum)
掌握PHP 8.1枚举类型,创建强类型常量集合。 · 难度:入门 · +15XP
什么是枚举?
PHP 8.1正式引入了枚举(Enum),它是一种用户定义的数据类型,包含一组有限的命名常量。枚举提供了类型安全,避免使用魔法字符串或数字。
基本枚举
enum Status {
case Active;
case Inactive;
case Banned;
}
function checkStatus(Status \$status): string {
return match (\$status) {
Status::Active => '用户活跃',
Status::Inactive => '用户未活跃',
Status::Banned => '用户被封禁',
};
}
echo checkStatus(Status::Active);
回退枚举(Backed Enum)
可以为枚举值关联标量值(int或string)。
enum Color: string {
case Red = '#FF0000';
case Green = '#00FF00';
case Blue = '#0000FF';
}
echo Color::Red->value; // 输出:#FF0000
枚举方法
枚举可以定义方法,提供行为逻辑。
enum OrderStatus: int {
case Pending = 0;
case Shipped = 1;
case Delivered = 2;
public function label(): string {
return match ($this) {
self::Pending => '待发货',
self::Shipped => '已发货',
self::Delivered => '已送达',
};
}
}
echo OrderStatus::Pending->label(); // 待发货
练习提示
在下方代码中,定义一个新的枚举Size(Small, Medium, Large),并添加一个方法inches()返回对应的尺寸(10, 12, 14)。