【无标题】

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
相关推荐
阿洛学长3 分钟前
最新PHPStudy安装教程(小皮V8.1)
php
Jun6264 分钟前
QT(5)-第三方日志系统
开发语言·数据库·qt
冰暮流星7 分钟前
javascript建立对象之构造函数
开发语言·javascript·ecmascript
keykey6.14 分钟前
PyTorch 入门实战:从张量到训练循环
开发语言·人工智能·深度学习·机器学习
消失的旧时光-194318 分钟前
Kotlin 协程设计思想(七):为什么 Kotlin 要设计 SupervisorJob 和 supervisorScope?
android·开发语言·kotlin
Full Stack Developme21 分钟前
SpringMVC multipart 文件上传
java·开发语言
得一录22 分钟前
ModuleNotFoundError: No module named ‘llama_index.llms
开发语言·人工智能
j7~25 分钟前
【C++】类和对象(下)--详解之再探构造函数,友元,static成员,类型转换等
开发语言·c++·类型转换·友元·匿名对象·内部类·编译器优化
稷下元歌26 分钟前
7天学会plc加机器视觉关于运动控制部份,配套视频在bib
开发语言·c++·git·vscode·python·docker·pip
薇茗26 分钟前
【C++】 类与对象 基础篇
开发语言·c++·基础语法·类与对象