如何迭代枚举
我想迭代枚举:
enum Shapes
{
case RECTANGLE;
case SQUARE;
case CIRCLE;
case OVAL;
}
如果这样做,我会得到形状
const无法定义:
foreach (Shapes as $shape) { }
我提供的最好的解决方案是手动为枚举创建数组:
$shapes = [
Shapes::RECTANGLE,
Shapes::SQUARE,
Shapes::CIRCLE,
Shapes::OVAL,
];
foreach ($shapes as $shape) { }
有什么更好的方法可以迭代枚举吗?
I want to iterate over enum:
enum Shapes
{
case RECTANGLE;
case SQUARE;
case CIRCLE;
case OVAL;
}
I get Shapes
const not defined if I do this:
foreach (Shapes as $shape) { }
The best solution I came with is to manually create array for enum:
$shapes = [
Shapes::RECTANGLE,
Shapes::SQUARE,
Shapes::CIRCLE,
Shapes::OVAL,
];
foreach ($shapes as $shape) { }
Is there any better way to iterate over the enum?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 cases()喜欢的枚举列表这:
输出是:
对于PHP 8.1及更大。
请参阅: php fiddle
You can generates a list of cases on an enum with cases() like this:
The output of this is:
for PHP 8.1 and greater.
See: PHP Fiddle
您可以尝试
形状:: case()
,它返回给定枚举的所有情况的数组。You can try
Shapes::cases()
,it returns an array of all cases of a given Enum.