【无标题】

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
相关推荐
CoderCodingNo20 分钟前
【GESP】C++五级真题(数论考点) luogu-P11961 [GESP202503 五级] 原根判断
开发语言·c++
wqdian_com21 分钟前
中文域名的准确展示能否堵住网络钓鱼攻击“后门”?
服务器·安全·php
乾元24 分钟前
网络切片的自动化配置与 SLA 保证——5G / 专网场景中,从“逻辑隔离”到“可验证承诺”的工程实现
运维·开发语言·网络·人工智能·网络协议·重构
代码游侠35 分钟前
应用——Web服务器项目代码解析
运维·服务器·开发语言·前端·笔记·html
Sirens.37 分钟前
Java异常处理解析:从防御式编程到自定义异常类
java·开发语言·笔记·学习·github·javac
lsx20240638 分钟前
MySQL 运算符
开发语言
逆境清醒42 分钟前
python教程总目录(更新中ing。。。)
开发语言·python
CC.GG1 小时前
【Qt】常用控件----显示类控件(QLabel、QLCDNumber、QProgressBar、QCalendarWidget)
开发语言·数据库·qt
程芯带你刷C语言简单算法题1 小时前
Day43~实现一个算法求一个数字的树根
c语言·开发语言·算法·c
Chase_______1 小时前
【JAVA基础指南(四)】快速掌握类和对象
java·开发语言