【无标题】

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
相关推荐
武子康2 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
悠悠~飘3 小时前
18.PHP基础-递归递推算法
算法·php
怪兽20143 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
ClearLiang3 小时前
Kotlin-协程的挂起与恢复
开发语言·kotlin
彭同学学习日志3 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
海域云赵从友3 小时前
破解跨境数据传输瓶颈:中国德国高速跨境组网专线与本地化 IP 的协同策略
开发语言·php
咚咚王者3 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓4 小时前
使matplot显示支持中文和负号
开发语言·python
syt_biancheng5 小时前
Day3算法训练(简写单词,dd爱框框,3-除2!)
开发语言·c++·算法·贪心算法
864记忆5 小时前
Qt Network 模块中的函数详解
开发语言·网络·qt