【无标题】

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
相关推荐
不要em0啦几秒前
从0开始学python:函数与数据容器
开发语言·python
zfj3219 分钟前
java线程的不同状态下调用interrupt()方法后的行为及注意事项
java·开发语言·interrupt·线程中断·线程状态
XLYcmy39 分钟前
高级密码猜测生成器AdvancedPasswordGenerator密码生成器程序详细分析
开发语言·python·算法·网络安全·开发工具·源代码·口令安全
廋到被风吹走41 分钟前
【Java】【Jdk】Jdk17->Jdk21
java·开发语言
2201_761199041 小时前
7.statefulset
开发语言·kubernetes·php
永远前进不waiting1 小时前
C复习——3
c语言·开发语言
yenggd1 小时前
wireshark常规用法
测试工具·wireshark·php
Edward.W1 小时前
Python实现人物剪影转ASCII艺术生成器
开发语言·python
天天进步20151 小时前
Python全栈项目--校园智能停车管理系统
开发语言·python
盼哥PyAI实验室2 小时前
我用 Coze + Python,从 0 搭了一个“能真正用”的 AI 律师函系统
开发语言·人工智能·python