通过字符串从枚举中获取案例

Get Case from enum by string

我正在寻找一个简单的解决方案来通过字符串获取枚举的大小写。 有 BackedEnums。例如:

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

但我不想为了得到那个结果而写同一个词两次。有没有 BackedEnums 的本机方法来获取案例? 我想要这样的东西:

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

或者我需要为此编写自己的功能吗?例如:

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

有没有更好的方法来达到同样的效果?

有一个这样的内部名称getter。

Status::OK->name;

这将 return Ok

Status::OK->value;

这将return值

从值中获取大小写。使用这个

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

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

ReflectionEnum 就是答案。在 php8.1 枚举的 rfc 中有一章 Reflection

你有方法 getCase(string $name) 并结合 getValue() 你得到了枚举。使用该函数,您可以通过字符串值获取大小写。

您的示例如下所示:

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

最好与 ExceptionHandler 一起使用,因为传输的字符串如果未找到,可能会在 ReflectionException

中结束