作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想通过名称获取 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
如果你想模仿 from
和 tryFrom
枚举函数,你还可以添加:
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/
我是一名优秀的程序员,十分优秀!