Skip to content

QuickStartLibs/Enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 

Repository files navigation

Enum Library

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.

Features

  • 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.

Installation

Simply require the class file in your script:

require_once 'path/to/src/Enum.php';

Usage

1. Static Usage (Recommended)

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]

2. Dynamic Usage

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; // 100

API Reference

Static Methods

  • isValid($value): Returns true if the value exists in the enum, false otherwise.
  • toArray(): Returns an associative array of all enum constants and their values.

Dynamic Methods

  • new Enum(...): Constructor accepts a list of string keys to auto-assign values, or an array of key=>value pairs.

About

The enum Library for Claritie

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages