php枚举使用实践

所属分类:php | 浏览:8 | 发布于 2026-06-02

之前要在php中实现枚举效果,要使用过 类 + 常量 + 静态方法 的方式,现在发现php8.1开始,已经可以使用原生Enum了。

 

1、字符串枚举

<?php

namespace app\common\enum;

/**
 * 通用状态枚举
 */
enum StatusEnum: int
{
    // 枚举项
    case DISABLE = 0;  // 禁用
    case ENABLE  = 1;  // 启用

    /**
     * 获取描述文本
     */
    public function getDesc(): string
    {
        return match ($this) {
            self::DISABLE => '禁用',
            self::ENABLE  => '启用',
        };
    }

    /**
     * 获取全部枚举数组(适配 TP 下拉框、字典)
     * @return array
     */
    public static function getList(): array
    {
        $list = [];
        foreach (self::cases() as $item) {
            $list[] = [
                'value' => $item->value,
                'label' => $item->getDesc()
            ];
        }
        return $list;
    }

    /**
     * 根据值获取文本
     */
    public static function getLabel(int $value): string
    {
        $enum = self::tryFrom($value);
        return $enum?->getDesc() ?? '未知状态';
    }

    /**
     * 校验值是否合法
     */
    public static function checkValue(int $value): bool
    {
        return self::tryFrom($value) !== null;
    }
}

2、控制器中调用

<?php
namespace app\index\controller;

use app\common\enum\StatusEnum;

class Index
{
    public function index()
    {
        // 1. 直接使用枚举值
        $status = StatusEnum::ENABLE->value;
        echo $status; // 1

        // 2. 根据值获取文字描述(列表页渲染)
        echo StatusEnum::getLabel(1); // 启用

        // 3. 下拉框数据源(前端 select/elementUI 等)
        $selectData = StatusEnum::getList();
        var_dump($selectData);

        // 4. 参数校验
        $inputVal = 2;
        if (!StatusEnum::checkValue($inputVal)) {
            return '状态值不合法';
        }

        // 5. 强类型判断
        $data = StatusEnum::DISABLE;
        if ($data === StatusEnum::DISABLE) {
            echo '当前为禁用状态';
        }
    }
}

3、结合模型获取器,自动把数字转为文本

<?php
namespace app\index\model;

use think\Model;
use app\common\enum\StatusEnum;

class User extends Model
{
    /**
     * 状态获取器
     */
    public function getStatusTextAttr($value, $data)
    {
        return StatusEnum::getLabel($data['status'] ?? 0);
    }
}

查询后直接使用 $user->status_text 即可展示文字。

4、扩展模版:字符串类型枚举

<?php

namespace app\common\enum;

/**
 * 订单类型枚举
 */
enum OrderTypeEnum: string
{
    case NORMAL = 'normal';
    case GROUP  = 'group';
    case SECKILL = 'seckill';

    public function getDesc(): string
    {
        return match ($this) {
            self::NORMAL  => '普通订单',
            self::GROUP   => '拼团订单',
            self::SECKILL => '秒杀订单',
        };
    }

    public static function getList(): array
    {
        $list = [];
        foreach (self::cases() as $item) {
            $list[] = ['value' => $item->value, 'label' => $item->getDesc()];
        }
        return $list;
    }

    public static function getLabel(string $value): string
    {
        $enum = self::tryFrom($value);
        return $enum?->getDesc() ?? '未知类型';
    }

    public static function checkValue(string $value): bool
    {
        return self::tryFrom($value) !== null;
    }
}

 

使用规范 & 最佳实践

1、命名规范

  • 枚举类名:XXXEnum 后缀(例:OrderStatusEnum、PayEnum)
  • 常量/枚举项:全大写 + 下划线(例:ORDER_WAIT、PAY_SUCCESS)

2、必带方法

  • getLabel():值转文字(列表 / 详情页)
  • getList():下拉框数据源
  • checkValue():参数合法性校验

 

 

海涛博客(https://haitaoblog.com)属于海涛个人博客,欢迎浏览使用

联系方式:qq:52292959 邮箱:52292959@qq.com W23

备案号:粤ICP备18108585号 友情链接