Rishiraj Purohit
Rishiraj Dev


Rishiraj Dev


Enumeration in PHP

Rishiraj Purohit's photo
Rishiraj Purohit
·Feb 10, 2021·

2 min read

tldr; php 8.1 will introduce enum as a new data type derived from classes and will behave like objects.

Enum syntax in PHP

enum Status{
    case Draft;
    case Published;
    case Archived;

long gone are the days of php being mocked for missing features. The world of PHP is catching up with new features introduced every release.

In PHP 8.1 one of the most interesting features being added to the language is the data type called enum (or Enumeration)

enum has existed for a long time in other languages where it acts as a set of possible values grouped in a structured way such that type safety can be guaranteed.

For example, a model called post might have a field called status which can be supplied a string value from the code calling the function setStatus(string $status). Generally, we would like to perform some validation to make sure the status makes sense.

While there are many ways to do just that starting from a function checking the value using an in_array($status, self::VALID_STATUS_ARRAY) to having a POJO class called Status with methods to return the status that you want to pass to the model.

But the most widely accepted way is to have a specific data type called enum as shown above.

php 8.1 finally is in the last stages of the RFC that adds just that to the language along with a few helpful functions like enum_exists

Enums will behave like standard php objects and will work with functions like is_a, get_class and will have magic methods like __CLASS__

I hope you liked this post, I wrote about enum in detail here where I go deep into explaining all available features in php enum along with some limitations and restrictions.

I also list possible ways to use enum today in your code using some well-known packages.

How do you feel about enum finally coming to PHP and do you think there are still some features you would like to be added to the language? let me know in the comments.

Did you find this article valuable?

Support Rishiraj Purohit by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this