DEV Community


Posted on

How to Use Enums in PHP 8.1 With Practical Examples

Enumerations, or enums for short, are a new feature in PHP 8.1. Enums are a way of representing a fixed number of values. Enums can be used to represent things like days of the week, months of the year, or even colors. Enums can make your code more readable and maintainable.

Enums can be thought of as a set of named constants. The values in an Enum must be unique and can be any scalar type (integer, float, string, or boolean). Enums are declared using the enum keyword.

Basic Syntax

Here’s what a simple enum looks like:

enum PostStatus {
    case Published;
    case InReview;
    case Draft;
Enter fullscreen mode Exit fullscreen mode

The case keyword, previously part of switch statements, is used to delineate the specific values the enum accepts. Values are referenced in the same way as class constants:

$published = PostStatus::Published;
Enter fullscreen mode Exit fullscreen mode

Enums in PHP 8.1 with Practical Examples.

PHP 8.1: Enums in Depth Video tutorial

How to use the Enums of PHP 8.1 in Laravel

Top comments (0)