DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Ellis
Ellis

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)

Stop sifting through your feed.

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.