PHP枚举与状态管理完全指南
PHP枚举与状态管理完全指南PHP8.1正式引入了枚举类型。这是PHP类型系统的一个重要增强。枚举让状态管理更安全更清晰。今天说说枚举的使用。枚举定义一组有限的可能值。phpenum OrderStatus{case Pending;case Paid;case Shipped;case Delivered;case Cancelled;}function processOrder(OrderStatus $status): string{return match ($status) {OrderStatus::Pending 待支付,OrderStatus::Paid 已支付,OrderStatus::Shipped 已发货,OrderStatus::Delivered 已签收,OrderStatus::Cancelled 已取消,};}$status OrderStatus::Paid;echo processOrder($status) . \n;echo $status-name . \n;?字符串回退枚举可以存储到数据库。phpenum UserRole: string{case Admin admin;case Editor editor;case User user;public function label(): string{return match ($this) {self::Admin 管理员,self::Editor 编辑,self::User 普通用户,};}public function permissions(): array{return match ($this) {self::Admin [create, read, update, delete],self::Editor [create, read, update],self::User [read],};}}$role UserRole::from(admin);echo $role-label() . \n;echo $role-can(delete) ? 有权限 : 无权限 . \n;foreach (UserRole::cases() as $role) {echo {$role-name}: {$role-value} - {$role-label()}\n;}?枚举在订单状态管理中的应用。phpenum PaymentStatus: string{case Pending pending;case Processing processing;case Completed completed;case Failed failed;case Refunded refunded;public function canRefund(): bool{return in_array($this, [self::Completed, self::Processing]);}public function isFinal(): bool{return in_array($this, [self::Completed, self::Failed, self::Refunded]);}}class Payment{public function __construct(public int $id,public float $amount,public PaymentStatus $status PaymentStatus::Pending) {}public function complete(): void{if ($this-status ! PaymentStatus::Processing) throw new RuntimeException(不能完成);$this-status PaymentStatus::Completed;}public function refund(): void{if (!$this-status-canRefund()) throw new RuntimeException(不能退款);$this-status PaymentStatus::Refunded;}}$payment new Payment(1, 99.99);$payment-status PaymentStatus::Processing;$payment-complete();echo 状态: {$payment-status-value}\n;echo 可退款: . ($payment-status-canRefund() ? 是 : 否) . \n;?枚举让状态管理更加类型安全避免了用字符串或整数表示状态时的拼写错误和无效值问题。枚举和数据库的配合也很自然可以用value存储到数据库的字符串字段。