【无标题】

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
相关推荐
Ramble_Naylor13 分钟前
Rust深度解读:异步流(Async Streams)与生成器的处理艺术
开发语言·后端·rust
努力实干21 分钟前
简单工厂模式(Simple Factory Pattern)——C++
开发语言·c++·简单工厂模式
熊猫钓鱼>_>24 分钟前
平行视界兼容模式与魔法变量配置避坑【鸿蒙心迹】
运维·服务器·开发语言·笔记·华为·harmonyos·openharmony
大鹏说大话32 分钟前
PHP 大文件上传解决方案:分片上传完整思路
开发语言·php
Wang's Blog1 小时前
Java 项目实战:交友项目 - 我的访客:需求说明
java·开发语言·交友
niucloud-admin1 小时前
NIUCLOUD PHP SAAS上门家政使用文档--服务订单:订单回访
php
布莱克6052 小时前
C++ 中堆和栈的区别详解
开发语言·c++·栈·堆
像风一样自由20202 小时前
3.Dockerfile如何构建一个Python算法镜像
开发语言·人工智能·python·大模型
大黄说说3 小时前
Composer 常见报错汇总:镜像、依赖冲突、环境坑一站式排查
php·composer
安易算力3 小时前
智算中心网络架构:RDMA/IB/以太网选型深度解析与优化实践
网络·架构·php