Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Case from enum by string

Tags:

php

enums

php-8.1

I search for a simple solution to get the case of an enum by a string. There are BackedEnums. For example:

<?php
enum Status: string
{
    case OK = "OK";
    case FAILED = "FAILED";
    ...
}
$status = Status::tryFrom("OK"); // or from("OK");

But I don't want to write the same word twice for getting that result. Is there a native way to get the case without having BackedEnums? I want something like:

<?php
enum Status
{
    case OK;
    case FAILED;
    ...
}
$status = Status::get("OK"); //returns Status::OK;

Or do I need to write my own funcionality for that? For example:

enum Status
{
    case OK;
    case FAILED;    
    public static function get(string $name): null|Status
    {
        $name = strtoupper(trim($name));
        if(empty($name))
            return null;

        foreach(Status::cases() as $status)
        {
            if($status->name == $name)
                return $status;
        }
        return null;
    }
}

Status::get("OK"); // -> Status::OK

Is there a better way to achieve the same?

like image 331
philsak Avatar asked May 11 '26 18:05

philsak


2 Answers

There is an internal name getter like this.

Status::OK->name;

This will return Ok

Status::OK->value;

This will return the value

To get the case from the value. Use this

$case = Status::tryFrom('Ok')

https://www.php.net/manual/en/backedenum.tryfrom.php

like image 92
joeb Avatar answered May 14 '26 07:05

joeb


ReflectionEnum is the answer. In the rfc for enums in php8.1 is a chapter Reflection

There you have the method getCase(string $name) and in combination with getValue() you get the enum. With that function you can get the case via a string value.

Your Example would look like this:

$status = (new ReflectionEnum("Status"))->getCase("OK")->getValue();

Best used with an ExceptionHandler since the transmitted string, if not found, could end up in a ReflectionException

like image 36
oikodomo Avatar answered May 14 '26 08:05

oikodomo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!