update page now

Examples

Example #1 Basic limited values

<?php

enum SortOrder
{
case
Asc;
case
Desc;
}

function
query($fields, $filter, SortOrder $order = SortOrder::Asc)
{
/* ... */
}
?>

The query() function can now proceed safe in the knowledge that $order is guaranteed to be either SortOrder::Asc or SortOrder::Desc. Any other value would have resulted in a TypeError , so no further error checking or testing is needed.

Example #2 Advanced exclusive values

<?php

enum UserStatus: string
{
case
Pending = 'P';
case
Active = 'A';
case
Suspended = 'S';
case
CanceledByUser = 'C';

public function
label(): string
{
return match(
$this) {
self::Pending => 'Pending',
self::Active => 'Active',
self::Suspended => 'Suspended',
self::CanceledByUser => 'Canceled by user',
};
}
}
?>

In this example, a user's status may be one of, and exclusively, UserStatus::Pending, UserStatus::Active, UserStatus::Suspended, or UserStatus::CanceledByUser. A function can type a parameter against UserStatus and then only accept those four values, period.

All four values have a label() method, which returns a human-readable string. That string is independent of the "machine name" scalar equivalent string, which can be used in, for example, a database field or an HTML select box.

<?php

foreach (UserStatus::cases() as $case) {
printf('<option value="%s">%s</option>\n', $case->value, $case->label());
}
?>

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 1 note

up
20
php-net at mentordosnerds dot com
2 years ago
Additional use-case examples:
<?php
trait EnumNamesTrait
{
 abstract public static function cases(): array;
 
 public static function names(): array
 {
 return array_map(fn($enum) => $enum->name, static::cases());
 }
}
trait EnumValuesTrait
{
 abstract public static function cases(): array;
 
 public static function values(): array
 {
 return array_map(fn($enum) => $enum->value, static::cases());
 }
}
trait EnumArraySerializableTrait
{
 use EnumNamesTrait;
 use EnumValuesTrait;
 
 public static function array(): array
 {
 return array_combine(static::names(), static::values());
 }
}
trait EnumJsonSerializableTrait
{
 use EnumArraySerializableTrait;
 
 public static function jsonSerialize(): string
 {
 return json_encode(static::array());
 }
}
enum Suit: string
{
 case Clubs = '♣';
 case Diamonds = '♦';
 case Hearts = '♥';
 case Spades = '♠';
 
 use EnumJsonSerializableTrait;
 
 public const DEFAULT = self::Hearts;
 
 public static function default(): static
 {
 return self::DEFAULT;
 }
}
var_dump(
 Suit::cases(),
 Suit::values(), 
 Suit::names(),
 Suit::array(),
 Suit::jsonSerialize(),
 Suit::default(),
);
+add a note

AltStyle によって変換されたページ (->オリジナル) /