PHP 8.1.15 Released!

枚举值清单

无论是纯粹枚举还是回退枚举,都实现了一个叫 UnitEnum 的内部接口。 UnitEnum 包含了一个静态方法: cases()。 按照声明中的顺序,cases() 返回了打包的 array,包含全部定义的条目。

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

为 Enum 手动定义 cases() 方法会导致 fatal 错误。

add a note

User Contributed Notes 2 notes

up
9
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
1 month 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