An In-Depth Guide to PHP 8.1: Enums
PHP 8.1 added Enums, this allows us to set a defined number of possible values for an array.
Join the DZone community and get the full member experience.
Join For FreeEnums or enumerations are a new feature introduced in PHP 8.1 that contains a defined number of possible values you can use. When creating an app, you often come across scenarios where you have a predetermined list of options to select from, for instance:
- A blog entry can be published, in the draft, or in review.
- A player may be a medic, soldier, engineer,
- A ticket may be VIP, standing, or seated,
- and so on ...
Basic Syntax
We can create the Enum by using the enum
keyword and defining the possible cases that are valid for this structure.
enum PostType {
case Draft;
case Published;
case InReview;
}
Next, we can update our function that requires a PostType,
but this time we're not just expecting an integer. Instead, we are telling our function to expect a variable of type PostType
.
class Post {
public function __construct(public string $title, public PostType $type){}
}
Pure vs Backed Enums
You may have noticed that using PostType::Published
in a database query is not as straightforward as it once was because your database most likely wants to store this type as an integer (draft = 0, published = 1, etc.).
Enums have various flavors to accomplish it. In the preceding example, we simply defined a few potential cases without assigning a value to those options. They are referred to as pure enums.
If we want to be able to attach values to an enum, these are called backed enums, and they work pretty much in the same way.
Let's begin by adding values to our enum cases (we are attaching value and are setting the return type for the enum as well)
enum PostType: int {
case Draft = 0;
case Published = 1;
case Unpublished = 2;
}
Now we can ask for the corresponding value for any of the cases in the enum by calling the value:
$post = new Post('Hello', PostType::Published);
echo "Post Type is: " . $post->type->value; // Post Type is: 1
Conclusion
Enums are a great addition to PHP for making it easier to come up with a data type that allows you to pick from a pre-defined set of choices with matching values.
Published at DZone with permission of Razet Jain. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments