Understanding PHP Enums: A Simple Guide

Blockchain

PHP 8.1 introduced us to Enums, which are a way of managing fixed sets of values in an easy manner. Up until Enums existed, the standards for managing these fixed sets ranged from using constants to even using strings, both of which leave plenty of room for errors and make code harder to maintain.

What Are Enums?

Enumerations in short called "Enums", allow you to define a set of named values that a variable may hold. In PHP, there are two types of Enums: Pure Enums and Backed Enums.

  1. Pure Enums: These are simple Enums without any values. They are useful when you only need to represent a fixed set of options.
  2. Backed Enums: These Enums have associated values, which can be either strings or integers. They’re useful when you need both a name and a value for each Enum case.

Pure Enums Example

Let’s start with pure Enums. Here’s an example:

enum Status {
    case Active;
    case Inactive;
    case Pending;
}

In this example, Status is a pure Enum with three possible values: Active, Inactive, and Pending. It’s a clean way to represent different statuses in your application.

How to Use Pure Enums:

function updateStatus(Status $status): void {
    if ($status === Status::Active) {
        echo "User is active";
    }
}

updateStatus(Status::Active);  // Outputs: User is active

In the code above, the function updateStatus takes a Status Enum as an argument. It checks if the status is Active and prints a message.

Backed Enums Example

Now, let’s look at backed Enums. These are more flexible because each case has an associated value:

enum PaymentStatus: string {
    case Paid = 'paid';
    case Pending = 'pending';
    case Failed = 'failed';
}

Here, PaymentStatus is a backed Enum with string values. Each status (Paid, Pending, Failed) is linked to a specific string.

In this example, the function getStatusMessage takes a PaymentStatus Enum and returns a corresponding message. This is a clear and concise way to handle different payment statuses.

function getStatusMessage(PaymentStatus $status): string {
    return match($status) {
        PaymentStatus::Paid => 'Payment Completed',
        PaymentStatus::Pending => 'Payment Pending',
        PaymentStatus::Failed => 'Payment Failed',
    };
}

echo getStatusMessage(PaymentStatus::Paid);  // Outputs: Payment Completed

We can also add methods in Enums, see below code;

enum OrderStatus {
    case Placed;
    case Shipped;
    case Delivered;
    case Cancelled;

    public function isFinalStatus(): bool {
        return match($this) {
            self::Delivered, self::Cancelled => true,
            default => false,
        };
    }
}

// Usage
$status = OrderStatus::Delivered;
echo $status->isFinalStatus();  // Outputs: 1 (true)

Advantages of Using Enums

Here’s why Enums are a game-changer in PHP:

  • Type Safety: Ensures that only valid values are used, reducing bugs.
  • Readability: Makes code more understandable and self-explanatory.
  • Maintainability: Adding or updating options becomes easier and less error-prone.

Wrapping Up

Enums are a great way to make your PHP code more reliable and easier to understand. They reduce errors, improve readability, and simplify maintenance. If you’re using PHP 8.1 or later, start using Enums to make your projects cleaner and more efficient.

For more details, check out the PHP 8.1 release notes.

Enums might seem like a small change, but they can make a big difference in your code quality. Give them a try and see how they can improve your next project!

Recent blog

House
Enhancing Application Tracking with Laravel Context

Explore how to utilize Laravel's context for improved tracking and debugging. Enhance your application's insights and manage data more effectively.

Nodejs
js
wordpress
tailwind
figma
bootstrap
html
nuxt
angular
react
vuejs
nextjs

Stay updated with our weekly newsletter

No Spam. Only high quality content and updates of our products.

Join 20,000+ other creators in our community

Discount imageStar image