Enumerations in PHP 8.1 RFC

PHP is getting more and more features. Enumerations in PHP are one of the latest proposals. Description for enumerations in PHP is described withing this request for comments

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. Similarly, enum names and case names are both case insensitive. (With the same caveat about autoloading on case sensitive file systems that already applies to classes generally.)

For example, we could start by defining class like enum Suit with various cases, i.e. case Hearts

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

Then we utilize defined cases by calling them like Suit::Diamonds;

If we would have, for example, a function pick_a_card which accepts one attribute Suit $suit we could provide any enum value from enum Suit. However, if we would try to provide direct string value, this woudl throw a TypeError, because of strong typing.

$val = Suit::Diamonds;

function pick_a_card(Suit $suit) { ... }

// OK

// OK

// throws TypeError

If you are interested in the current state of this feature implementation you can find it here https://github.com/php/php-src/pull/6489/files

Personal note: I believe enum types would be a great fit for PHP, especially taken into account the strongly typed direction in which PHP moves since 7.x versions.

I was attending the Symfony 2020 conference and there was one great lecture about PHP 8.0 and new features including JIT. I wrote an article about insights I got from this lecture called What is new in PHP 8.0: SymfonyWorld 2020