How to use PHP 1 Enums In PHP
With PHP 8.1, native support for enums was introduced, offering a more robust and type-safe way to define and use enums. This approach uses enum classes to define the enum values and a method to convert them to strings.
Example: The example usage demonstrates creating an enum class and converting an enum value to a string.
<?php
enum StatusEnum: string {
case PENDING = 'Pending';
case APPROVED = 'Approved';
case REJECTED = 'Rejected';
public function toString(): string {
return $this->value;
}
}
// Driver code
$status = StatusEnum::PENDING;
$statusString = $status->toString();
echo "Status: $statusString";
?>
Output:
Status: Pending
PHP Program to Convert Enum to String
Enumerations, or enums are a convenient way to represent a fixed set of named values in programming. In PHP, native support for enums was introduced in PHP 8.1. If you are working with an earlier version of PHP, or if you want to explore alternative approaches, you may need a way to convert enums to strings.
Table of Content
- Using Class Constants
- Associative Arrays
- Using PHP 8.1 Enums