PHP
Enumerations
Web Development
Coding
Programming Languages

Enumerations on PHP

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Enumerations, or Enums, are a feature in many programming languages used to define a variable that can hold a set of predefined constants. Before PHP 8.1, PHP did not natively support enumerations and developers resorted to using classes or constants. However, from PHP 8.1 onwards, native enumeration support has been introduced. Enumerations are particularly valuable for defining a domain of closely related constants and can greatly enhance code readability and maintainability.

Understanding Enums in PHP

Enums are a way to group together related values which share a common characteristic. Imagine you have a set of user roles in an application – without enums, these might be represented as strings or integers, leading to potential errors due to typos or incorrect values. With enums, these can be grouped into a single user-defined type.

Syntax and Usage

An enum is defined in a similar way to a class. Here’s a basic example of an enum defining possible user roles:

php
1enum UserRole: string {
2    case Admin = 'admin';
3    case Editor = 'editor';
4    case Subscriber = 'subscriber';
5}

The enum UserRole can take one of three specified cases, each being a constant and having a string value. The enum defined with a backing type (: string) explicitely defines the type of values the enum cases hold.

Accessing Enum Cases

Enum cases are accessed using the scope resolution operator (::):

php
$role = UserRole::Admin;

echo $role->value;   // Output: admin

Methods in Enums

PHP permits methods to be added to enums; allowing encapsulating related functionality within the enum itself:

php
1enum UserRole: string {
2    case Admin = 'admin';
3    case Editor = 'editor';
4    case Subscriber = 'subscriber';
5
6    public function canEdit(): bool {
7        return $this === self::Admin || $this === self::Editor;
8    }
9}
10
11$role = UserRole::Editor;
12echo $role->canEdit();  // Output: 1 (true)

Comparison of Enum Cases

Enums can be compared directly using the identity operator (===), ensuring that both the name and value match:

php
if ($role === UserRole::Admin) {
    echo 'User is an admin.';
}

Enums with Enums

Enums can have methods that return other enums, enhancing the ability to manage related constants coherently:

php
1enum UserStatus: string {
2    case Active = 'active';
3    case Inactive = 'inactive';
4    case Suspended = 'suspended';
5}
6
7enum UserRole: string {
8    case Admin = 'admin';
9    case Editor = 'editor';
10
11    public function defaultStatus(): UserStatus {
12        return $this === self::Admin ? UserStatus::Active : UserStatus::Inactive;
13    }
14}

Benefits of Using Enums

The use of enums leads to safer code by reducing errors like misspelling and providing a fixed set of values. Enums are also self-documenting; the definition of an enum tells other programmers which values are permissible.

Summary Table

Here is a summary of key points regarding enumerations in PHP:

FeatureDescription
Type SafetyEnums ensure only valid values are used.
ReadabilityEnums improve code clarity compared to plain strings or numbers.
MethodsEnums can encapsulate related functionality.
Backing TypeEnums can be backed by int or string types.
ComparabilityEnums can be compared using identity checks.

Conclusion

The introduction of native enums in PHP 8.1 provides PHP developers with an additional powerful tool for writing robust and maintainable code. While the concept might be familiar to those coming from other languages, PHP’s implementation offers a blend of simplicity and power, making it a notable feature for modern PHP development. Implementing enums can greatly aid in improving the clarity and reliability of the code, especially in systems with a clear set of fixed values or states.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions