【无标题】

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
相关推荐
虾球xz26 分钟前
CppCon 2015 学习:Reactive Stream Processing in Industrial IoT using DDS and Rx
开发语言·c++·物联网·学习
aischang1 小时前
统信桌面专业版如何使用python开发平台jupyter
开发语言·python·jupyter·统信uos
狐凄1 小时前
Python实例题:Python计算概率论
开发语言·python·概率论
q567315232 小时前
分布式增量爬虫实现方案
开发语言·分布式·爬虫·python
勤奋的知更鸟2 小时前
LLaMA-Factory和python版本的兼容性问题解决
开发语言·python·llama-factory
CIb0la2 小时前
Ai自动补全编程工具:llama vscode
运维·开发语言·学习·测试工具·程序人生
1candobetter2 小时前
JAVA后端开发——多租户
java·开发语言
freyazzr2 小时前
C++八股 | Day3 | 智能指针 / 内存管理 / 内存分区 / 内存对齐
开发语言·c++
序属秋秋秋2 小时前
《C++初阶之入门基础》【普通引用 + 常量引用 + 内联函数 + nullptr】
开发语言·c++·笔记
星辰离彬2 小时前
Java 高级泛型实战:8 个场景化编程技巧
java·开发语言·后端·程序人生