【无标题】

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
相关推荐
随丶芯10 分钟前
IDEA安装leetcode-editor插件
java·开发语言
Ccjf酷儿24 分钟前
C++语言程序设计 (郑莉)第六章 数组、指针和字符串
开发语言·c++
禹曦a25 分钟前
Java实战:Spring Boot 构建电商订单管理系统RESTful API
java·开发语言·spring boot·后端·restful
superman超哥26 分钟前
精确大小迭代器(ExactSizeIterator):Rust性能优化的隐藏利器
开发语言·后端·rust·编程语言·rust性能优化·精确大小迭代器
芒克芒克26 分钟前
虚拟机类加载机制
java·开发语言·jvm
陌路2027 分钟前
C++28 STL容器--array
开发语言·c++
FPGAI35 分钟前
Python之函数
开发语言·python
csbysj202038 分钟前
NumPy Ndarray 对象
开发语言
Z1Jxxx39 分钟前
删除字符串2
开发语言·c++·算法
小CC吃豆子42 分钟前
Qt的信号与槽机制
开发语言·数据库·qt