【无标题】

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
相关推荐
阿里嘎多学长3 小时前
2026-02-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管
啊吧怪不啊吧5 小时前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
CeshirenTester5 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例
发现你走远了5 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
游乐码6 小时前
c#类和对象
开发语言·c#
黎雁·泠崖6 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
懒惰成性的7 小时前
12.Java的异常
java·开发语言
-To be number.wan7 小时前
Python数据分析:时间序列数据分析
开发语言·python·数据分析
zorro_z7 小时前
实战SimpleBlog(二):博客发布与管理
php
前路不黑暗@7 小时前
Java项目:Java脚手架项目的通用组件的封装(六)
java·开发语言·spring