PHP 8.1 – ENUMS are here!

PHP 8.1 – ENUMS are here!

limited selections, enums

Limit your variables with pre-selected values setup by using new scalar type of enum and by as cool and fun as JAVA or C# developers!

Enumerations are built on top of classes and objects. That means, except where otherwise noted, “how would Enums behave in situation X” can be answered “the same as any other object instance.” They would, for example, pass an object type check. Enum names are case-insensitive, but subject to the same caveat about autoloading on case-sensitive file systems that already applies to classes generally. Case names are internally implemented as class constants, and thus are case-sensitive.

Basic enumerations

enum Suit {
  case Hearts;
  case Diamonds;
  case Clubs;
  case Spades;
}

Usage:

function pick_a_card(Suit $suit) { ... }
 
$val = Suit::Diamonds;
 
pick_a_card($val);        // OK
pick_a_card(Suit::Clubs); // OK
pick_a_card('Spades');    // TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment