This is a story of a software developer, a very normal one, that used to write code in Java, and enjoyed working with enumeration to define a closed set of data.

That same developer one day started to work with PHP and realized that they were missing, which grew quite a sadness in him :(

But, finally, that developer is no longer sad since version 8.1 of PHP added enumeration to the language.

How does it work?

Enums are similar to classes, it defines a new type, which has a fixed, limited number of possible allowed values.

This declaration creates a new simple enumerated type UserState, which has four valid values: UserState::RegisteredUserState::ActivatedUserState::Disabled, and UserState::Blocked.

A function may be type-checked against an enumerated type, in which case only values of that type may be passed.

By default, cases are not intrinsically backed by a scalar value. That is, User::Registered is not equal to 0. Instead, each case is backed by a singleton object of that name.

#programming #php

PHP 8.1 — Welcome Enumeration
1.10 GEEK