Leveraging match and enum in Modern PHP: A Beginner's Guide

Leveraging match and enum in Modern PHP: A Beginner's Guide
Photo by ennif pendahl / Unsplash

PHP has evolved significantly over the years, and with the introduction of PHP 8.0 and PHP 8.1, two powerful features were added to its toolkit: match expressions and enum types. These additions are aimed at making code more expressive, readable, and maintainable. If you're just getting started with them, let me walk you through how they work individually and how you can combine them to create more structured and readable code.

The Beauty of match Expressions

The match expression is an elegant replacement for the older switch statement. It allows for more concise and strict comparisons. Unlike switch, match does not fall through to other cases accidentally, and it performs strict type comparisons.

Here's a simple example:

$action = 'delete';

$result = match($action) {
    'create' => 'Creating an item',
    'update' => 'Updating an item',
    'delete' => 'Deleting an item',
    default => 'Unknown action',
};

echo $result; // Outputs: Deleting an item

In the above example, you can see that match returns a value directly, which means we can assign its result to a variable immediately. This makes it not only shorter but also more expressive.

Introducing enum Types

In PHP 8.1, enum was introduced to provide a structured way to define a fixed set of possible values for a type. This is especially useful when you need to represent a finite set of states or options, like actions, statuses, or categories. With enum, you avoid the risk of passing invalid values, which can make your code more robust.

Let’s take a look at a simple example of an enum:

enum Action: string {
    case Create = 'create';
    case Update = 'update';
    case Delete = 'delete';
}

Here, we define an enum called Action with three cases: Create, Update, and Delete. Each of these cases represents a specific value.

Combining match and enum

Now, let’s see how we can use enum types alongside match expressions to make the code even more powerful and expressive.

enum Action: string {
    case Create = 'create';
    case Update = 'update';
    case Delete = 'delete';
}

function handleAction(Action $action): string {
    return match($action) {
        Action::Create => 'Creating an item',
        Action::Update => 'Updating an item',
        Action::Delete => 'Deleting an item',
    };
}

echo handleAction(Action::Delete); // Outputs: Deleting an item

In this example, we’ve tied our match expression directly to an enum. This means that we’re now protected from invalid values. The function handleAction only accepts one of the defined Action enum values, making the code self-documenting and less error-prone. If someone tries to pass an invalid action, they’ll get a clear error from PHP.

Why Use This Combination?

The combination of match and enum allows you to create more readable and maintainable code. Here’s why:

  1. Strict typing: With enum, you ensure that only valid values are passed around in your code, reducing the chance of bugs.
  2. Clear structure: The match expression is more concise and readable than switch, especially when dealing with multiple cases.
  3. Maintainability: As your application grows, using enum and match helps to organize related values and actions logically. You can add new enum cases easily and update the related match expressions in one place.

What Else to Keep in Mind?

Error handling: When using match, be mindful of the default case. If there’s no match for a given value, PHP will throw an error unless you provide a default case. This can be useful in situations where you want strict behavior, but remember to handle unexpected inputs appropriately.

Enums with methods: Enums can also have methods attached to them. This means you can group behavior directly with the enum cases. For example, if each action required a specific log message, you could add a method to your enum that returns the correct log message based on the case.

enum Action: string {
    case Create = 'create';
    case Update = 'update';
    case Delete = 'delete';

    public function logMessage(): string {
        return match($this) {
            self::Create => 'Log: Create action performed',
            self::Update => 'Log: Update action performed',
            self::Delete => 'Log: Delete action performed',
        };
    }
}

echo Action::Delete->logMessage(); // Outputs: Log: Delete action performed

This not only keeps your code organized but also reduces the risk of duplicating logic across your application.

Finally

The match expression and enum types are two of the most exciting features in modern PHP. They make your code clearer, more expressive, and less prone to errors. Whether you're building APIs, web apps, or even command-line tools, incorporating these features into your projects can help you write cleaner and more maintainable code.

By understanding how to mix and match these features, you’ll be better equipped to write PHP code that is robust, flexible, and easy to read. So the next time you find yourself writing repetitive switch statements or handling arbitrary values, remember that match and enum are there to help you simplify and structure your code more effectively.

Support Us

Subscribe to Buka Corner

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe