I want to get the value of an Enum in PHP by its name. My enum is like:
enum Status : int
{
case ACTIVE = 1;
case REVIEWED = 2;
// ...
}
Status::from(2)
can be used to get "REVIEWED"
, but how can I resolve the value from the name stored in a string ?
Well, it seems there is not any built-in solution in PHP. I've solve this with a custom function:
enum Status : int
{
case ACTIVE = 1;
case REVIEWED = 2;
// ...
public static function fromName(string $name): string
{
foreach (self::cases() as $status) {
if( $name === $status->name ){
return $status->value;
}
}
throw new \ValueError("$name is not a valid backing value for enum " . self::class );
}
}
Then, I simply use Status::fromName('ACTIVE')
and get 1
If you want to mimic the from
and tryFrom
enum functions, you can also add:
public static function tryFromName(string $name): string|null
{
try {
return self::fromName($name);
} catch (\ValueError $error) {
return null;
}
}