Listagem de valores

Tanto Pure Enums quanto Backed Enums implementam uma interface interna chamada UnitEnum. UnitEnum inclui um método estático cases(). cases() retorna um array embalado com todos os Casos definidos na ordem de declaração.

<?php
Naipe
::cases();
// Produz: [Naipe::Copas, Naipe::Ouros, Naipe::Paus, Naipe::Espadas]
?>

Definir manualmente um método cases() em uma Enum resultará em um erro fatal.

add a note

User Contributed Notes 2 notes

up
7
theking2 at king dot ma
6 months 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
1
ratsimbasitraka at gmail dot com
25 days 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