0
0
PhpConceptBeginner · 3 min read

What is enum in PHP: Simple Explanation and Usage

enum in PHP is a special type that lets you define a set of named values, making your code easier to read and safer. It was introduced in PHP 8.1 to group related constants under one type, like days of the week or user roles.
⚙️

How It Works

Think of an enum as a list of named options you can choose from, like a menu at a restaurant. Instead of using random numbers or strings, you use these names to make your code clearer and less error-prone.

When you create an enum in PHP, you define a fixed set of possible values. This means you can only use those values, which helps prevent mistakes like typos or invalid inputs. It’s like having a checklist that only allows approved choices.

Under the hood, PHP treats enums as special objects with named cases. You can compare them, switch on them, and even add methods to them for extra behavior.

💻

Example

This example shows how to define an enum for days of the week and use it in a function to print a message.

php
<?php
enum DayOfWeek {
    case Monday;
    case Tuesday;
    case Wednesday;
    case Thursday;
    case Friday;
    case Saturday;
    case Sunday;
}

function greet(DayOfWeek $day): string {
    return match($day) {
        DayOfWeek::Saturday, DayOfWeek::Sunday => "It's weekend!",
        default => "It's a weekday.",
    };
}

echo greet(DayOfWeek::Monday) . "\n";
echo greet(DayOfWeek::Sunday) . "\n";
Output
It's a weekday. It's weekend!
🎯

When to Use

Use enums when you have a fixed set of related values that a variable can hold. This helps make your code more readable and reduces bugs caused by invalid values.

For example, enums are great for:

  • Representing days of the week, months, or seasons.
  • Defining user roles like Admin, Editor, and Viewer.
  • Specifying states in a process, such as Pending, Approved, or Rejected.

They make your code easier to maintain and understand, especially in larger projects.

Key Points

  • Enums group related constants under one type.
  • They improve code clarity and safety by limiting possible values.
  • Introduced in PHP 8.1, enums support methods and can be used in type hints.
  • Enums can be backed by scalar values like strings or integers for easier storage.

Key Takeaways

Enums define a fixed set of named values to improve code clarity and safety.
PHP enums were introduced in version 8.1 and can be used as types in functions.
Use enums to represent related options like days, roles, or states.
Enums prevent invalid values by restricting choices to predefined cases.
Backed enums allow associating scalar values with enum cases for storage or display.