【无标题】

PHP 使用常量实现枚举类

php 复制代码
<?php
abstract class Enum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function getEnumValue($constant) {
        $constants = self::getConstants();
        return $constants[$constant] ?? null;
    }
}

class StatusCode extends Enum {
    const OK = 200;
    const NOT_FOUND = 404;
    // ... 其他状态码
}

// 使用类常量直接访问枚举值
$statusCode = StatusCode::getEnumValue(StatusCode::OK);
echo $statusCode; // 输出 200
相关推荐
基德爆肝c语言1 小时前
Qt—信号和槽
开发语言·qt
geovindu1 小时前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
故事和你912 小时前
洛谷-算法2-1-前缀和、差分与离散化1
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
励志的小陈8 小时前
贪吃蛇(C语言实现,API)
c语言·开发语言
Makoto_Kimur8 小时前
java开发面试-AI Coding速成
java·开发语言
laowangpython8 小时前
Gurobi求解器Matlab安装配置教程
开发语言·其他·matlab
wengqidaifeng8 小时前
python启航:1.基础语法知识
开发语言·python
观北海8 小时前
Windows 平台 Python 极简 ORB-SLAM3 Demo,从零实现实时视觉定位
开发语言·python·动态规划
Ulyanov10 小时前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
码界筑梦坊10 小时前
357-基于Java的大型商场应急预案管理系统
java·开发语言·毕业设计·知识分享