【无标题】

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
相关推荐
浔川python社4 分钟前
《C++ 小程序编写系列》(第四部):实战:简易图书管理系统(类与对象篇)
java·开发语言·apache
浔川python社8 分钟前
《C++ 小程序编写系列》(第五部):实战:多角色图书管理系统(继承与多态篇)
开发语言·c++
CC.GG24 分钟前
【Qt】信号和槽
开发语言·数据库·qt
是席木木啊24 分钟前
基于MinIO Java SDK实现ZIP文件上传的方案与实践
java·开发语言
一起养小猫34 分钟前
《Java数据结构与算法》第四篇(四):二叉树的高级操作查找与删除实现详解
java·开发语言·数据结构·算法
ALex_zry43 分钟前
C++20/23标准对进程间共享信息的优化:从传统IPC到现代C++的演进
开发语言·c++·c++20
IMPYLH1 小时前
Lua 的 OS(操作系统) 模块
开发语言·笔记·后端·游戏引擎·lua
YGGP1 小时前
【Golang】LeetCode 287. 寻找重复数
开发语言·leetcode·golang
吴佳浩 Alben1 小时前
Go 1.22 通关讲解
开发语言·数据库·golang
黎雁·泠崖1 小时前
指针家族高阶篇:字符指针、数组指针、函数指针及转移表应用
c语言·开发语言