【无标题】

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
相关推荐
未来之窗软件服务7 分钟前
计算机考试-C语言 应用题—东方仙盟
c语言·开发语言·仙盟创梦ide·东方仙盟·计算机考试
想你依然心痛7 分钟前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
我是一颗柠檬10 分钟前
【Java项目技术亮点】EXPLAIN深度分析与慢查询治理
android·java·开发语言
luj_176814 分钟前
草酸与烟酸对消化及糖代谢的影响解析
服务器·c语言·开发语言·经验分享·算法
fei_sun19 分钟前
【SystemVerilog】SystemVerilog与C语言的接口
c语言·开发语言
W是笔名30 分钟前
python___容器类型的数据___序列
开发语言·python
☆cwlulu31 分钟前
try-throw-catch异常捕获流程
开发语言·c++
漂亮的摩托36 分钟前
深感一无所长,准备试着从零开始写个富文本编辑器
开发语言·php
要开心吖ZSH43 分钟前
Java事务与MySQL事务的关系及MVCC通俗解析
java·开发语言·mysql·mvcc
火星校尉1 小时前
一场数据基建与消费场景的跨界实验
java·前端·数据库·python·php