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