Liste de valeurs

Les Enums pures et les Enums soutenues implémentent toute deux une interface interne nommée UnitEnum. UnitEnum comprend une méthode statique cases(). cases() renvoie un tableau compact de tous les cas définis dans l'ordre de leur déclaration.

<?php

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

La définition manuelle d'une méthode cases() sur un Enum entraînera une erreur fatale.

add a note add a note

User Contributed Notes 2 notes

up
13
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
-8
ratsimbasitraka at gmail dot com
1 year ago
enum Priority {
    case Left;
    case Right;
}

// Does not work as default parameter
public function selectPriorities(array $priorities = Priority::cases()) {
    Priority::cases() // works here
}
To Top