【无标题】

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
相关推荐
曹轲恒41 分钟前
Java中断
java·开发语言
施棠海1 小时前
监听与回调的三个demo
java·开发语言
時肆4851 小时前
C语言造轮子大赛:从零构建核心组件
c语言·开发语言
赴前尘2 小时前
golang 查看指定版本库所依赖库的版本
开发语言·后端·golang
de之梦-御风2 小时前
【C#.Net】C#开发的未来前景
开发语言·c#·.net
知乎的哥廷根数学学派2 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
de之梦-御风3 小时前
【C#.Net】C#在工业领域的具体应用场景
开发语言·c#·.net
sunfove3 小时前
将 Python 仿真工具部署并嵌入个人博客
开发语言·数据库·python
Learner3 小时前
Python类
开发语言·python
科技块儿3 小时前
使用强大的离线IP地址定位库IP数据云获取数据信息
网络·tcp/ip·php