Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum value by name stored in a string in PHP

Tags:

php

enums

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 ?

like image 449
Diego Garcia Avatar asked Sep 09 '25 15:09

Diego Garcia


2 Answers

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;
    }
}
like image 177
Diego Garcia Avatar answered Sep 12 '25 13:09

Diego Garcia


Update for PHP8.3:

$name = 'REVIEWED';
Status::{$name}->value;
Status::{'REVIEWED')->value;

https://php.watch/versions/8.3/dynamic-class-const-enum-member-syntax-support

Previously:

You can use reflection for Backed case:

$reflection = new ReflectionEnumBackedCase(Status::class, 'REVIEWED');
$reflection->getBackingValue(); // 2
$reflection->getValue() // Status::REVIEWED if you need case object

Or enum reflection:

$reflection = new ReflectionEnum(Status::class);
$reflection->getCase('REVIEWED')->getValue()->value // 2

see also ReflectionEnumUnitCase

like image 33
fela Avatar answered Sep 12 '25 11:09

fela