【无标题】

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
相关推荐
啵啵鱼爱吃小猫咪5 小时前
机械臂阻抗控制github项目-mujoco仿真
开发语言·人工智能·python·机器人
似水明俊德5 小时前
02-C#
开发语言·c#
oem1105 小时前
C++中的享元模式实战
开发语言·c++·算法
似水明俊德5 小时前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
leonkay5 小时前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
Allnadyy6 小时前
【C++项目】从零实现高并发内存池(一):核心原理与设计思路
java·开发语言·jvm
雅欣鱼子酱6 小时前
Type-C供电PD协议取电Sink芯片ECP5702,可二端头分开供电调整亮度,适用于LED灯带户外防水超亮灯条方案
c语言·开发语言
似水明俊德6 小时前
07-C#
开发语言·c#
浩子智控6 小时前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd6 小时前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python