【无标题】

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
相关推荐
sinat_602035363 小时前
模块与包的导入
运维·服务器·开发语言·python
恋雨QAQ3 小时前
python函数和面向对象
开发语言·python
天雪浪子3 小时前
Python入门教程之逻辑运算符
开发语言·python
落羽的落羽3 小时前
【C++】特别的程序错误处理方式——异常机制
开发语言·c++
通达的K4 小时前
Java实战项目演示代码及流的使用
java·开发语言·windows
云:鸢4 小时前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
离越词5 小时前
C++day8作业
开发语言·c++·windows
℃CCCC5 小时前
请求库-axios
开发语言·华为·网络请求·harmonyos·deveco studio·axios请求·arkts编程
ling__i5 小时前
java day18
java·开发语言