How to use Enum in PHP

Updated: January 9, 2024 By: Guest Contributor Post a comment

Overview

Enums, short for enumerations, are a data type that allows you to define a set of labeled values. In PHP, Enums were introduced in PHP 8.1, providing a robust way to define a list of possible values for a variable. This tutorial walks through the usage of Enums in PHP with code examples from basic to advanced implementations.

Introduction to Enum

The Enum is a built-in class in PHP 8.1 and later versions. Before PHP 8.1, developers created a list of possible values using constants within a class. With the support of Enums, you can create more semantic and type-safe code. This tidy syntax results in a self-documenting API that inherently limits the values your code can work with, reducing bugs and making your intention clearer to other developers.

enum Status {
 case Pending;
 case Approved;
 case Denied;
}

This simple example creates an Enum called Status with three possible values: Pending, Approved, and Denied.

Using Enums in functions or methods

To employ Enums in your functions, specify the Enum type in the function signature, which ensures that only valid, predefined Enum values can be passed as arguments. This mechanism also enhances static analysis tools’ ability to catch potential errors.

function processApplication(Status $status): void {
 // Process application based on status
 switch ($status) {
  case Status::Pending:
   // Handle pending
   break;
  case Status::Approved:
   // Handle approved
   break;
  case Status::Denied:
   // Handle denied
   break;
 }
}

In this function, processApplication, the parameter $status is type-hinted to Status, therefore it can only accept values of the Enum type Status.

Backed Enums

PHP’s Enums can also be ‘backed’ by a scalar value, such as a string or an integer. Backed Enums define a scalar value for each case, which can be used to serialize the Enum values, communicate over the wire, or store them in a database.

enum UserRole: string {
 case Admin = 'admin';
 case Editor = 'editor';
 case Subscriber = 'subscriber';
}

Here, each case of the UserRole enum has an associated string value, a feature known as a ‘backed enum’.

Methods and Properties in Enums

Beyond simply listing cases, Enums in PHP can include methods and properties, allowing for encapsulation and behavior related to the Enum cases.

enum HttpStatus: int {
 case Ok = 200;
 case NotFound = 404;
 case InternalServerError = 500;

 public function description(): string {
  return match($this) {
   self::NotFound => 'The requested resource was not found.',
   self::InternalServerError => 'The server encountered an internal error.',
   default => 'OK'
  };
 }
}

This Enum, HttpStatus, assigns an integer to each case and defines a method description() that returns a human-readable message based on the case.

Using Enums with Classes

Enums can integrate with classes to provide a streamlined way to work with predefined lists in an object-oriented manner.

class PaymentGateway {
 private HttpStatus $status;

 public function setStatus(HttpStatus $status): void {
  $this->status = $status;
 }

 public function getStatusDescription(): string {
  return $this->status->description();
 }
}

In this example, the PaymentGateway class has a property $status of type HttpStatus, enforcing that only valid Enum values can be used for the status.

Comparing Enum Cases

Comparing Enums is straightforward because each case is a singleton, meaning there’s only one instance of each.

$status1 = Status::Pending;
$status2 = Status::Approved;

if ($status1 === $status2) {
 // This will not execute since $status1 and $status2 are different cases
}

Here we compare two Enum cases using the identity operator (===), which is possible because each case is its own unique instance.

Advanced Usages of Enums

Enums can take on more complex use cases such as implementing interfaces or using traits. This flexibility allows Enums to be as powerful and adaptable as any other class type in PHP.

interface Describable {
 public function description(): string;
}

enum HTTPMethod: string implements Describable {
 case Get = 'GET';
 case Post = 'POST';
 case Put = 'PUT';

 public function description(): string {
  return match($this) {
   self::Get => 'Retrieves resources.',
   self::Post => 'Creates resources.',
   self::Put => 'Updates resources.',
  };
 }
}

Here, the Enum HTTPMethod implements the Describable interface to provide a description for each HTTP Method.

Conclusion

Enums bring a powerful means for developers to express fixed sets of values in a semantically meaningful and type-safe way in PHP 8.1 and newer. Through several examples, this tutorial has shown how Enums can refine and strengthen your PHP applications, leading to more robust and maintainable code. Start using Enums and harness the potential of this elegant language feature for your next PHP project.