【无标题】

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
相关推荐
yugi9878382 分钟前
基于MATLAB的延迟求和(DAS)波束形成算法实现
开发语言·算法·matlab
冷雨夜中漫步5 分钟前
Python入门——字符串
开发语言·python
Yvonne爱编码5 分钟前
Java 接口学习核心难点深度解析
java·开发语言·python
黎雁·泠崖23 分钟前
Java继承入门:概念+特点+核心继承规则
java·开发语言
x70x8040 分钟前
Go中nil的使用
开发语言·后端·golang
星辰徐哥1 小时前
Java程序的编译与运行机制
java·开发语言·编译·运行机制
Sylvia-girl1 小时前
线程安全问题
java·开发语言·安全
CC.GG1 小时前
【C++】C++11----智能指针
开发语言·c++
沛沛老爹1 小时前
Web开发者转型AI安全实战:Agent Skills敏感数据脱敏架构设计
java·开发语言·人工智能·安全·rag·skills
曹轲恒1 小时前
Java并发包atomic原子操作类
java·开发语言