値のリスト

Pure Enum と Backed Enum は、 共に内部インターフェイス UnitEnum を実装しています。 UnitEnum には static メソッド cases() が含まれています。 cases() は、 定義されている全ての case を宣言された順に含めた配列を返します。

<?php

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

列挙型において、手動で cases() メソッドを定義すると、致命的なエラーが発生します。

add a note

User Contributed Notes 2 notes

up
23
theking2 at king dot ma
3 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-srcimg-srcfont-srcscript-srcstyle-src
up
0
anhaia dot gabriel at gmail dot com
11 months ago
If you want to get all the values of the Enum in a list of `string`, you might do something like this:<?phpenum 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