【无标题】

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
相关推荐
snow@li12 分钟前
SpringBoot:AOP日志切面全景梳理/原理+流程+实战+避坑
java·开发语言·spring boot
Nil20813 分钟前
C++ emplace_back 与 push_back 详解
开发语言·c++
clear sky .36 分钟前
[freertos源码阅读]task.c任务篇
c语言·开发语言
XR1234567881 小时前
工业园区整体组网,方案对比怎么选?
开发语言·php
东东最爱敲键盘1 小时前
day9.C++多态之虚函数
开发语言·c++
码云数智-园园1 小时前
类似小鹅通的知识付费小程序平台有哪些
开发语言
snow@li1 小时前
Java:跨平台原理与JDK、JRE、JVM全景深度解析
java·开发语言·jvm
Livia要学习1 小时前
Python闭包
开发语言·jvm·python
覆东流1 小时前
2.Java程序基础
java·开发语言·后端
ttwuai1 小时前
Go 后台定时任务启停不生效怎么办?先查调度同步链路
开发语言·后端·golang