PHP 8.1 Enum (枚举) 根据名字取得枚举 作者: Chuwen 时间: 2023-09-21 分类: PHP 灵感来源于:https://github.com/php/php-src/issues/9352#issuecomment-1216839118 ```php $enumClass * @param string $name * @return T|null */ function tryFromName(string $enumClass, string $name) { $constName = $enumClass . '::' . $name; return is_subclass_of($enumClass, UnitEnum::class) && defined($constName) ? constant($constName) : null; } // enum(Gender::UNKNOWN) var_dump(tryFromName(Gender::class, 'UNKNOWN')); // enum(Gender::MALE) var_dump(tryFromName(Gender::class, 'MALE')); // enum(Gender::FEMALE) var_dump(tryFromName(Gender::class, 'FEMALE')); // NULL var_dump(tryFromName(Gender::class, 'null')); ``` 标签: PHP, Enum