【无标题】

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
相关推荐
(Charon)12 分钟前
【C++】网络缓冲区设计(二):Ring Buffer环形缓冲区、head/tail与跨界读写
开发语言·c++
Java后端的Ai之路23 分钟前
LangChain Deep Agents 从入门到企业实战
开发语言·人工智能·python·langchain·deepagents
会飞的拖把26 分钟前
Python文件操作详解:从文件读写到os、shutil模块实战
开发语言·python
RS迷途小书童31 分钟前
Python 解析大疆无人机 SRT 字幕日志
开发语言·python·无人机
点心的游戏开发世界1 小时前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
会飞的拖把1 小时前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python
reasonsummer1 小时前
【办公类-115-01】20260906育儿知识(家园小报)批量制作(2026年9月-2027年6月)
开发语言·数据库·c#
君顾11 小时前
智慧场馆解决方案小程序系统实战:从架构设计到上线指南
java·开发语言·智慧场馆
zhougl9961 小时前
Dockerfile实战教程
java·开发语言·spring boot
FfHUCisI2 小时前
Golang 网络轮询器 netpoll:把阻塞 IO 变成事件通知
开发语言·网络·golang