ๅ€คใฎใƒชใ‚นใƒˆ

Pure Enum ใจ Backed Enum ใฏใ€ ๅ…ฑใซๅ†…้ƒจใ‚คใƒณใ‚ฟใƒผใƒ•ใ‚งใ‚คใ‚น UnitEnum ใ‚’ๅฎŸ่ฃ…ใ—ใฆใ„ใพใ™ใ€‚ UnitEnum ใซใฏ static ใƒกใ‚ฝใƒƒใƒ‰ cases() ใŒๅซใพใ‚Œใฆใ„ใพใ™ใ€‚ cases() ใฏใ€ ๅฎš็พฉใ•ใ‚Œใฆใ„ใ‚‹ๅ…จใฆใฎ case ใ‚’ๅฎฃ่จ€ใ•ใ‚ŒใŸ้ †ใซๅซใ‚ใŸ้…ๅˆ—ใ‚’่ฟ”ใ—ใพใ™ใ€‚

<?php
enum Suit
{
case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;
}

var_dump(Suit::cases());

enum
SuitBacked: string
{
case
Hearts = 'H';
case
Diamonds = 'D';
case
Clubs = 'C';
case
Spades = 'S';
}

var_dump(SuitBacked::cases());

ๅˆ—ๆŒ™ๅž‹ใซใŠใ„ใฆใ€ๆ‰‹ๅ‹•ใง cases() ใƒกใ‚ฝใƒƒใƒ‰ใ‚’ๅฎš็พฉใ™ใ‚‹ใจใ€่‡ดๅ‘ฝ็š„ใชใ‚จใƒฉใƒผใŒ็™บ็”Ÿใ—ใพใ™ใ€‚

๏ผ‹add a note

User Contributed Notes 2 notes

up
28
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-src
img-src
font-src
script-src
style-src
up
9
anhaia dot gabriel at gmail dot com ยถ
1 year 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());
    }
}

?>