PHPnews.io

PHP 8.1 is Getting Enumerations!

Written by colinodell.com - Blog / Original link on Feb. 17, 2021

The PHP RFC for enumerations just passed a 44-7 vote to be accepted as a new feature in the upcoming PHP 8.1 release!

Enumerations, also known as "enums", are a special data type that can only contain specific, predefined (or "enumerated") values. They behave somewhat similar to constants, in that their names can be referenced in code, but they allow for stronger typing.

The classic use case illustrated by the RFC is of an enum that defines different suits of playing cards:

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

From the RFC:

This declaration creates a new enumerated type named Suit, which has four and only four legal values: Suit::Hearts, Suit::Diamonds, Suit::Clubs, and Suit::Spades. Variables may be assigned to one of those legal values. A function may be type checked against an enumerated type, in which case only values of that type may be passed.

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

Enums can do more than just that - check out the RFC for a list of examples and capabilities.

I'm personally super excited about this feature and can't wait to start using them in my projects!

colinodell

« Celebrating pancake day the only way I know how - Make it a Blade + Alpine Component »