【无标题】

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
相关推荐
360智汇云7 分钟前
一次Redis超时引发的“冤案“
数据库·redis·php
JackieZhengChina10 分钟前
image-viewer-js 开源图片查看插件完整教程
开发语言·javascript·开源
ljs64827395120 分钟前
Linux 网络常用命令与端口基础详解
linux·网络·php
光影少年23 分钟前
react的View/Text/Image/ScrollView 常用组件注意事项
开发语言·前端·javascript·react.js·前端框架
库克克1 小时前
【C++】类和对象--类对象模型与大小计算
开发语言·jvm·c++
布朗克1681 小时前
Go 入门到精通-15-错误处理
开发语言·python·golang·错误处理
zzb15802 小时前
Zed 配置 Swift / iOS 开发
开发语言·ios·swift
北冥you鱼4 小时前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
这不小天嘛10 小时前
JAVA八股——J集合篇
java·开发语言
AOwhisky11 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发