【无标题】

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
相关推荐
青山是哪个青山3 分钟前
C++ 核心基础与面向对象 (OOP)
开发语言·c++
小明同学016 分钟前
[C++进阶]深入理解二叉搜索树
开发语言·c++·git·visualstudio
C+++Python11 分钟前
C++ vector
开发语言·c++·算法
莫问前路漫漫13 分钟前
Python包管理工具pip完整安装教程
开发语言·python
superman超哥14 分钟前
处理复杂数据结构:Serde 在实战中的深度应用
开发语言·rust·开发工具·编程语言·rust serde·rust数据结构
Java程序员威哥15 分钟前
Arthas+IDEA实战:Java线上问题排查完整流程(Spring Boot项目落地)
java·开发语言·spring boot·python·c#·intellij-idea
superman超哥24 分钟前
错误处理与验证:Serde 中的类型安全与数据完整性
开发语言·rust·编程语言·rust编程·rust错误处理与验证·rust serde
夔曦28 分钟前
【python】月报考勤工时计算
开发语言·python
fl17683129 分钟前
基于python实现PDF批量加水印工具
开发语言·python·pdf
Eugene__Chen42 分钟前
Java的SPI机制(曼波版)
java·开发语言·python