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;