PHP 8.4.2 Released!

枚举值清单

无论是纯粹枚举还是回退枚举,都实现了一个叫 UnitEnum 的内部接口。 UnitEnum 包含了一个静态方法: cases()。 按照声明中的顺序,cases() 返回了打包的 array,包含全部定义的条目。

<?php

Suit
::cases();
// 产生: [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades]
?>

为 Enum 手动定义 cases() 方法会导致 fatal 错误。

添加备注

用户贡献的备注 2 notes

up
23
theking2 at king dot ma
2 years ago
As ::cases() creates a Iteratable it is possible to use it in a foreach loop. In combination with value backed enum this can result in very compact and very readable code:

<?php
/** Content Security Policy directives */
enum CspDirective: String {
case Default =
"default-src";
case
Image = "img-src";
case
Font = "font-src";
case
Script = "script-src";
case
Style = "style-src";
}

/** list all CSP directives */
foreach( CspSource::cases() as $directive ) {
echo
$directive-> value . PHP_EOL;
}
?>
Which results in:
default-src
img-src
font-src
script-src
style-src
up
0
anhaia dot gabriel at gmail dot com
4 months ago
If you want to get all the values of the Enum in a list of `string`, you might do something like this:

<?php

enum MyEnum
: string
{
case
OPTION_A = 'option_a';
case
OPTION_B = 'option_b';
case
OPTION_C = 'option_c';

public static function
values(): array
{
return
array_map(fn ($case) => $case->value, self::cases());
}
}

?>
To Top