PHP 8.2.0 Beta 3 available for testing

Value listing

Both Pure Enums and Backed Enums implement an internal interface named UnitEnum. UnitEnum includes a static method cases(). cases() returns a packed array of all defined Cases in the order of declaration.

<?php
Suit
::cases();
// Produces: [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades]
?>

Manually defining a cases() method on an Enum will result in a fatal error.

add a note

User Contributed Notes 1 note

up
1
theking2 at king dot ma
1 month 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
To Top