【无标题】

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 分钟前
算法-拓扑排序-C
c语言·开发语言·算法
wangchen_08 分钟前
深入理解 C/C++ 强制类型转换:从“暴力”到“优雅”
java·开发语言·jvm
lly20240619 分钟前
CSS 颜色
开发语言
潲爺24 分钟前
《Java 8-21 高频特性实战(上):5 个场景解决 50% 开发问题(附可运行代码)》
java·开发语言·笔记·学习
资生算法程序员_畅想家_剑魔27 分钟前
算法-回溯-14
java·开发语言·算法
w_zero_one39 分钟前
Java的Vert.x框架结合Thymeleaf(TH)模板语言
java·开发语言·idea
咸鱼2.01 小时前
【java入门到放弃】网络
java·开发语言·网络
阿里嘎多学长1 小时前
2025-12-28 GitHub 热点项目精选
开发语言·程序员·github·代码托管
zmzb01031 小时前
C++课后习题训练记录Day58
开发语言·c++
会员果汁1 小时前
算法-并查集-C
c语言·开发语言·算法