Enums, introduced in PHP 8.1, provide a way to define a set of possible values for a type, offering a structured and type-safe alternative to constants. They are ideal for situations where you need to represent a fixed set of options, such as user roles, status codes, or any predefined list of values.
Basic Enum Syntax:
To declare an enum in PHP 8.1, you use the enum
keyword:
enum UserRole { case Admin; case Editor; case Subscriber; }
Here, UserRole
defines three possible values: Admin
, Editor
, and Subscriber
.
Using Enums
Enums can be used as types in function parameters, ensuring that only the defined values are allowed:
function getUserPermissions(UserRole $role): array { return match($role) { UserRole::Admin => ['create', 'edit', 'delete'], UserRole::Editor => ['create', 'edit'], UserRole::Subscriber => ['read'], }; } $role = UserRole::Admin; $permissions = getUserPermissions($role);
This setup guarantees that only valid roles can be passed to the function.
Backed Enums
Enums can also be associated with scalar values, like strings or integers:
enum Status: string { case Active = 'active'; case Inactive = 'inactive'; case Suspended = 'suspended'; } echo Status::Active->value; // Outputs: 'active'
Backed enums are useful when you need to map enum values to database entries or other external systems.
Enum Methods
PHP enums can contain methods for more complex logic:
enum OrderStatus { case Pending; case Shipped; case Delivered; public function isFinal(): bool { return $this === self::Delivered; } }
Here, OrderStatus
includes a method isFinal
to check if the status is Delivered
.
Conclusion:
Enums in PHP 8.1 bring type safety and clarity to your code by grouping related constants. They are especially useful when you need to ensure that a variable can only hold a predefined set of values, making your code more robust and easier to maintain.
Read Also :-
Fibers – Bringing Async Programming to PHP
HTML Code for Working With SASS CSS
Also Visit :-