【无标题】

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
相关推荐
读书札记20221 分钟前
Qt Creator 调试报错:Unable to create a debugging engine.
开发语言·qt
透明的玻璃杯1 分钟前
Qt Creator + Windows + Protobuf 最优方案(Mqqt通讯采用的方式)
开发语言·windows·qt
小书房6 分钟前
Kotlin协程的运行原理
android·开发语言·kotlin·协程
隐退山林7 分钟前
JavaEE进阶:SpringIoC&DI
java·开发语言·java-ee
水煮白菜王8 分钟前
Claude Code 全方位使用手册
java·开发语言·网络
Highcharts.js8 分钟前
金融Web App中的复杂时序数据可视化:从选型到高性能实践
开发语言·金融·highcharts·实战代码·响应式图表
郝学胜-神的一滴11 分钟前
跨平台 C++ 静态库编译实战:Linux/Windows/macOS 三端统一实现
linux·开发语言·c++·windows·软件构建
xyq202414 分钟前
XHR 请求详解
开发语言
ooseabiscuit15 分钟前
Laravel10.x重磅发布:新特性全解析
android·java·开发语言·mysql
沐知全栈开发19 分钟前
JavaScript while 循环详解
开发语言