A flexible PHP Enumeration library that supports both dynamic runtime enums and static class constant enums.
(php.net)
This design was implemented before PHP 8.1 Enum support. It was previously implemented as part of the Claritie Framework.
- Dynamic Enums: Create enums on the fly with automatic value assignment.
- Static Enums: Extend the class to create standard, type-safe enums using constants.
- Validation: Built-in validation to check if values are part of the enum.
- Metadata: Easily retrieve all defined enum keys and values.
Simply require the class file in your script:
require_once 'path/to/src/Enum.php';The recommended way to use this library is by extending the Enum class. This provides a structured and IDE-friendly way to define constants.
use Enum;
class UserRole extends Enum {
const ADMIN = 1;
const EDITOR = 2;
const SUBSCRIBER = 3;
}
// Accessing values
echo UserRole::ADMIN; // Output: 1
// Validating a value
if (UserRole::isValid(1)) {
echo "Valid role!";
}
// Getting all options
$roles = UserRole::toArray();
// Returns: ['ADMIN' => 1, 'EDITOR' => 2, 'SUBSCRIBER' => 3]You can also instantiate the Enum class directly to create enums at runtime.
// Initialize with values
$status = new Enum("PENDING", "ACTIVE", "ARCHIVED");
echo $status->PENDING; // 0
echo $status->ACTIVE; // 1
// Add new values dynamically
$status->DELETED = 99;
echo $status->DELETED; // 99
// Auto-increment logic
$status->UNKNOWN;
echo $status->UNKNOWN; // 100isValid($value): Returnstrueif the value exists in the enum,falseotherwise.toArray(): Returns an associative array of all enum constants and their values.
new Enum(...): Constructor accepts a list of string keys to auto-assign values, or an array of key=>value pairs.