如何获得枚举类型?
我想知道获得枚举的后盾类型的最佳方法是什么:
enum E: string {
case a = "A";
case b = "B";
}
我有一个接收enum
类名称为参数的函数,在函数中,我需要检查该类型是否由<<<代码> int 或字符串
或不是后面的枚举
。
//this function can be called like: foo(E::class)
function foo(string $enum) {
// here I need to check if $enum is backed by int or string or nothing
}
我已经尝试过get_parent_class
,但是它不起作用,因为备份的枚举
s没有继承后背类型,它们只是封闭的列表。 我知道我可以在enum
定义中放置一个静态功能,然后返回那里的类型,但是我想知道是否有更通用和优雅的方式?
I was wondering what is the best way to get an Enum's backed type:
enum E: string {
case a = "A";
case b = "B";
}
I have a function that receives an Enum
class name as the parameter and inside the function I need to check if the type is backed by int
or string
or it is not a Backed Enum
.
//this function can be called like: foo(E::class)
function foo(string $enum) {
// here I need to check if $enum is backed by int or string or nothing
}
I've already tried get_parent_class
, however it does not work since Backed Enum
s are not inheriting the back type and they are just closed lists.
I know I can put a static function inside the Enum
definition and return the type there, but I was wondering if there is a more general and elegant way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于php 8.2,您可以使用 felfection> felfection :
在行动中看到它。
Since PHP 8.2 you can use reflection:
See it in action.
对于任何寻求解决方案的人,这是 @Barmar建议的示例实现。
假设您的枚举至少有一个案例。
For anyone else looking for a solution, here's an example implementation of @Barmar's suggestion.
Assuming that your enum has at least a single case.
仍然假设枚举至少有一个案例,这似乎更简单
Still assuming enums have atleast a single case, this seems simpler