【无标题】

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
相关推荐
豐儀麟阁贵4 分钟前
4.5数组排序算法
java·开发语言·数据结构·算法·排序算法
Jane-66677727 分钟前
C语言——栈与队列
c语言·开发语言
“抚琴”的人29 分钟前
C# 取消机制(CancellationTokenSource/CancellationToken)
开发语言·c#·wpf·1024程序员节·取消机制
Halo_tjn33 分钟前
Java Map集合
java·开发语言·计算机
lsx20240635 分钟前
DOM 创建节点
开发语言
richxu202510012 小时前
C语言<<超全.超重要>>知识点总结
c语言·开发语言
2501_916008892 小时前
用多工具组合把 iOS 混淆做成可复用的工程能力(iOS混淆|IPA加固|无源码混淆|Ipa Guard|Swift Shield)
android·开发语言·ios·小程序·uni-app·iphone·swift
胎粉仔2 小时前
Swift 初阶 —— inout 参数 & 数据独占问题
开发语言·ios·swift·1024程序员节
Lizhihao_2 小时前
Python如何写Selenium全攻略
开发语言·python
「QT(C++)开发工程师」2 小时前
嵌入式Lua脚本编程核心概念
开发语言·lua