【无标题】

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
相关推荐
Wang's Blog15 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
吃好睡好便好18 小时前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab
yaoxin52112318 小时前
476. Java 反射 - 调用方法
java·开发语言
猫头虎18 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
bksczm19 小时前
Linux之日志和线程池、内存池
java·开发语言
笨蛋不要掉眼泪19 小时前
Java虚拟机:对象复活、引用强度与Stop-The-World
java·开发语言·jvm
code_pgf19 小时前
C/C++ 常用容器功能汇总
c语言·开发语言·c++
布朗克16819 小时前
Go 入门到精通-33-unsafe 与 CGO
开发语言·后端·golang·unsafe·cgo
个 人 练 习 生20 小时前
strcmp与strstr函数的模拟实现
c语言·开发语言·经验分享·学习·程序人生
1570925113420 小时前
【无标题】
开发语言·python·算法