【无标题】

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
相关推荐
眠りたいです2 分钟前
现代C++:C++11并发支持库
开发语言·c++·多线程·c++11·c++并发支持库
小灰灰搞电子9 分钟前
Rust可以取代C++么?
开发语言·c++·rust
保持低旋律节奏10 分钟前
linux——进程状态
android·linux·php
cat三三13 分钟前
java之异常
java·开发语言
奇树谦15 分钟前
【Qt实战】实现图片缩放、平移与像素级查看功能
开发语言·qt
我命由我1234522 分钟前
Python Flask 开发问题:ImportError: cannot import name ‘Markup‘ from ‘flask‘
开发语言·后端·python·学习·flask·学习方法·python3.11
wjs202425 分钟前
Go 语言指针
开发语言
wuguan_36 分钟前
C#:多态函数重载、态符号重载、抽象、虚方法
开发语言·c#
小信啊啊37 分钟前
Go语言数组与切片的区别
开发语言·后端·golang