gpt4 book ai didi

php - 通过存储在 PHP 字符串中的名称获取枚举值

转载 作者:行者123 更新时间:2023-12-05 08:24:50 25 4
gpt4 key购买 nike

我想通过名称获取 PHP 中枚举的值。我的枚举是这样的:

enum Status : int
{
case ACTIVE = 1;
case REVIEWED = 2;
// ...
}

Status::from(2) 可用于获取 "REVIEWED",但如何从存储在字符串中的名称解析值?

最佳答案

嗯,PHP 似乎没有任何内置的解决方案。我用自定义函数解决了这个问题:

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 );
}

}

然后,我只需使用 Status::fromName('ACTIVE') 并获得 1

如果你想模仿 fromtryFrom 枚举函数,你还可以添加:

public static function tryFromName(string $name): string|null
{
try {
return self::fromName($name);
} catch (\ValueError $error) {
return null;
}
}

关于php - 通过存储在 PHP 字符串中的名称获取枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71002391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com