⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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 = 200NotFound = 404ServerError = 500,并添加一个方法message()返回对应描述。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 90 篇
0 完成
🔥 0