PHP枚举类型与状态管理实践PHP8.1正式引入了枚举类型这是PHP类型系统的一个重要增强。枚举让状态管理更安全、更清晰。今天详细说说枚举的使用。枚举的基本用法。枚举定义一组有限的可能值。php// PHP8.1 枚举enum 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;// 枚举比较if ($status OrderStatus::Paid) {echo 订单已支付\n;}?回退枚举可以用标量值表示枚举方便存储到数据库php// 字符串回退枚举enum UserRole: string{case Admin admin;case Editor editor;case User user;case Guest guest;public function label(): string{return match ($this) {self::Admin 管理员,self::Editor 编辑,self::User 普通用户,self::Guest 访客,};}public function permissions(): array{return match ($this) {self::Admin [create, read, update, delete, manage],self::Editor [create, read, update],self::User [read],self::Guest [],};}public function can(string $permission): bool{return in_array($permission, $this-permissions());}}// 从数据库值创建枚举$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 HttpStatus: int{case Continue 100;case Ok 200;case Created 201;case NoContent 204;case MovedPermanently 301;case Found 302;case BadRequest 400;case Unauthorized 401;case Forbidden 403;case NotFound 404;case InternalServerError 500;case BadGateway 502;public function isError(): bool{return $this-value 400;}public function isSuccess(): bool{return $this-value 200 $this-value 300;}public function isRedirect(): bool{return $this-value 300 $this-value 400;}public function message(): string{return match ($this) {self::Ok OK,self::Created Created,self::NotFound Not Found,self::InternalServerError Internal Server Error,default Unknown,};}}$status HttpStatus::NotFound;echo {$status-value} {$status-message()}\n;echo $status-isError() ? 是错误状态 : 不是错误状态 . \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]);}public function nextStatuses(): array{return match ($this) {self::Pending [self::Processing, self::Failed],self::Processing [self::Completed, self::Failed],self::Completed [self::Refunded],self::Failed [],self::Refunded [],};}}class Payment{public function __construct(public int $id,public float $amount,public PaymentStatus $status PaymentStatus::Pending) {}public function process(): void{if ($this-status ! PaymentStatus::Pending) {throw new RuntimeException(当前状态不能处理);}$this-status PaymentStatus::Processing;}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;}public function fail(): void{$this-status PaymentStatus::Failed;}}$payment new Payment(1, 99.99);echo 初始状态: {$payment-status-value}\n;$payment-process();echo 处理后: {$payment-status-value}\n;$payment-complete();echo 完成后: {$payment-status-value}\n;echo 可以退款吗: . ($payment-status-canRefund() ? 是 : 否) . \n;?枚举和数据库的配合也很自然,可以用枚举的value存储到数据库的字符串或整数字段。枚举让状态管理更加类型安全避免了用字符串或整数表示状态时的拼写错误和无效值问题。
PHP枚举类型与状态管理实践
发布时间:2026/6/3 17:21:54
PHP枚举类型与状态管理实践PHP8.1正式引入了枚举类型这是PHP类型系统的一个重要增强。枚举让状态管理更安全、更清晰。今天详细说说枚举的使用。枚举的基本用法。枚举定义一组有限的可能值。php// PHP8.1 枚举enum 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;// 枚举比较if ($status OrderStatus::Paid) {echo 订单已支付\n;}?回退枚举可以用标量值表示枚举方便存储到数据库php// 字符串回退枚举enum UserRole: string{case Admin admin;case Editor editor;case User user;case Guest guest;public function label(): string{return match ($this) {self::Admin 管理员,self::Editor 编辑,self::User 普通用户,self::Guest 访客,};}public function permissions(): array{return match ($this) {self::Admin [create, read, update, delete, manage],self::Editor [create, read, update],self::User [read],self::Guest [],};}public function can(string $permission): bool{return in_array($permission, $this-permissions());}}// 从数据库值创建枚举$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 HttpStatus: int{case Continue 100;case Ok 200;case Created 201;case NoContent 204;case MovedPermanently 301;case Found 302;case BadRequest 400;case Unauthorized 401;case Forbidden 403;case NotFound 404;case InternalServerError 500;case BadGateway 502;public function isError(): bool{return $this-value 400;}public function isSuccess(): bool{return $this-value 200 $this-value 300;}public function isRedirect(): bool{return $this-value 300 $this-value 400;}public function message(): string{return match ($this) {self::Ok OK,self::Created Created,self::NotFound Not Found,self::InternalServerError Internal Server Error,default Unknown,};}}$status HttpStatus::NotFound;echo {$status-value} {$status-message()}\n;echo $status-isError() ? 是错误状态 : 不是错误状态 . \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]);}public function nextStatuses(): array{return match ($this) {self::Pending [self::Processing, self::Failed],self::Processing [self::Completed, self::Failed],self::Completed [self::Refunded],self::Failed [],self::Refunded [],};}}class Payment{public function __construct(public int $id,public float $amount,public PaymentStatus $status PaymentStatus::Pending) {}public function process(): void{if ($this-status ! PaymentStatus::Pending) {throw new RuntimeException(当前状态不能处理);}$this-status PaymentStatus::Processing;}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;}public function fail(): void{$this-status PaymentStatus::Failed;}}$payment new Payment(1, 99.99);echo 初始状态: {$payment-status-value}\n;$payment-process();echo 处理后: {$payment-status-value}\n;$payment-complete();echo 完成后: {$payment-status-value}\n;echo 可以退款吗: . ($payment-status-canRefund() ? 是 : 否) . \n;?枚举和数据库的配合也很自然,可以用枚举的value存储到数据库的字符串或整数字段。枚举让状态管理更加类型安全避免了用字符串或整数表示状态时的拼写错误和无效值问题。