0
0
PHPprogramming~5 mins

Enum backed values in PHP

Choose your learning style9 modes available
Introduction

Enums with backed values let you give each option a fixed value like a number or string. This helps when you want to connect names to real data.

When you want to represent fixed choices with specific values, like days of the week with numbers.
When you need to store or send enum values as strings or numbers in a database or API.
When you want to compare enum options by their values easily.
When you want to print or log meaningful values instead of just names.
When you want to convert values back to enum options safely.
Syntax
PHP
enum Name: type {
    case OPTION1 = value1;
    case OPTION2 = value2;
    // ...
}

The type can be int or string.

Each case must have a unique value of the specified type.

Examples
This enum uses strings as values to represent different statuses.
PHP
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Rejected = 'rejected';
}
This enum uses integers as values to represent directions.
PHP
enum Direction: int {
    case Up = 1;
    case Down = 2;
    case Left = 3;
    case Right = 4;
}
Sample Program

This program defines a backed enum for days with numbers. It prints the value for Monday and Friday, then converts the number 3 back to the enum and prints its name.

PHP
<?php

enum DayOfWeek: int {
    case Monday = 1;
    case Tuesday = 2;
    case Wednesday = 3;
    case Thursday = 4;
    case Friday = 5;
    case Saturday = 6;
    case Sunday = 7;
}

function printDayValue(DayOfWeek $day): void {
    echo "The value of {$day->name} is {$day->value}.\n";
}

printDayValue(DayOfWeek::Monday);
printDayValue(DayOfWeek::Friday);

// Convert value back to enum
$day = DayOfWeek::from(3);
echo "Day with value 3 is {$day->name}.\n";
OutputSuccess
Important Notes

You can use ::from(value) to get the enum case from a value. It throws an error if the value is invalid.

You can also use ::tryFrom(value) which returns null if the value is invalid.

Summary

Enum backed values link enum cases to fixed strings or numbers.

This helps when you want to store, compare, or display enum data easily.

Use from() or tryFrom() to convert values back to enum cases.