PHP 枚举
学习PHP 8.1引入的原生枚举类型,包括纯枚举、回退枚举和枚举方法。 · 难度:入门 · +15XP
什么是枚举?
枚举(Enum)是PHP 8.1引入的一种数据类型,用于定义一组有限的、具名的常量值。枚举让代码更清晰、类型更安全,避免了使用常量或字符串导致的错误。
定义枚举
使用enum关键字定义枚举:
<?php
enum OrderStatus {
case Pending;
case Processing;
case Shipped;
case Delivered;
case Cancelled;
}纯枚举与回退枚举
| 类型 | 说明 | 示例 |
|---|---|---|
| 纯枚举 | 无标量值 | enum Color { case Red; } |
| 回退枚举 | 可关联整数或字符串 | enum Status: int { case Active = 1; } |
代码示例
<?php
enum OrderStatus: string {
case Pending = 'pending';
case Shipped = 'shipped';
case Delivered = 'delivered';
public function label(): string {
return match($this) {
self::Pending => '待处理',
self::Shipped => '已发货',
self::Delivered => '已送达',
};
}
}
$status = OrderStatus::Shipped;
echo $status->label(); // 已发货
?>
枚举方法
枚举可以定义方法,让逻辑更内聚:
<?php
enum Month {
case January;
case February;
public function days(): int {
return match($this) {
Month::January => 31,
Month::February => 28,
};
}
}
echo Month::January->days(); // 31
练习提示
定义一个HttpStatus回退枚举(整型),包含OK = 200、NotFound = 404、ServerError = 500,并添加一个方法message()返回对应描述。