【无标题】

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
相关推荐
攻城狮凌霄4 小时前
PHP接单涨薪系列(七十一):如何用Neo4j构建借贷关系图谱?解析资金流水时空矩阵揪出“砍头息“和“循环贷“
矩阵·php·neo4j
Whisper_Sy4 小时前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 网络状态实现
android·java·开发语言·javascript·网络·flutter·php
Bony-4 小时前
Go语言垃圾回收机制详解与图解
开发语言·后端·golang
hmywillstronger4 小时前
【Rhino】【Python】 查询指定字段并cloud标注
开发语言·python
新缸中之脑4 小时前
Weave.js:开源实时白板库
开发语言·javascript·开源
我能坚持多久4 小时前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
leo__5205 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
二十雨辰5 小时前
[python]-函数
开发语言·python
码农水水5 小时前
中国邮政Java面试被问:容器镜像的多阶段构建和优化
java·linux·开发语言·数据库·mysql·面试·php
福楠5 小时前
C++ STL | map、multimap
c语言·开发语言·数据结构·c++·算法