Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 41 / 68

Enum (Enumerated Types) Basics

In this lesson you will learn about enums, available from PHP 8.1, so a fixed set of options can be handled safely. This is for anyone searching for "PHP enum how to use".

enum, available from PHP 8.1, creates an enumerated type representing a fixed set of options. Use it when you want to limit the possible values in advance, the way a traffic light only has red, green, and amber. Named constants convey intent far better than strings or numbers scattered through the code.

The sample code defines three cases - Red, Green, Blue - on a Color enum, reads the underlying value with Color::Red->value, and lists every option with Color::cases(). The : string declaration gives each case a string value.

A common stumbling block for beginners is that this is a relatively new feature available only from PHP 8.1. It will not run on older environments, so check your version. Before that, class constants were the usual substitute.

Enums can carry methods too, letting you define behaviour per option. It is an approach used in practice for values with a fixed set of possibilities, such as order statuses or user permission levels.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)