DEV Community

Rishiraj Purohit
Rishiraj Purohit

Posted on • Updated on • Originally published at rishiraj.dev

Enumeration in PHP

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;
}
Enter fullscreen mode Exit fullscreen mode

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

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

enum have existed for a long time in other languages where it acts as a set of possible values grouped together 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 as to make sure the status is one that 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 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 last stages of the RFC that adds just that to the language along with 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 details here where I go deep into the 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.

Top comments (2)

Collapse
 
dansilcox profile image
Dan Silcox

About time am I right!

Collapse
 
ri5hirajp profile image
Rishiraj Purohit

exactly