Div PHP Enum Solution

Installs: 14

Dependents: 0

Suggesters: 0

Security: 0

Stars: 4

Watchers: 0

Forks: 1

Open Issues: 0

pkg:composer/divengine/enum

1.0.2 2024-01-13 02:43 UTC

This package is auto-updated.

Last update: 2026-01-07 09:46:37 UTC


README

Div PHP Enum is a small class-based enum pattern for PHP. It predates PHP 8.1 native enums and is not a replacement for them. Use it when you need class hierarchies, polymorphic behavior, or compatibility with older PHP versions.

Why this library

  • Build enum taxonomies with inheritance.
  • Use type hints to constrain families of values.
  • Add behavior directly on each enum class.
  • Keep a tiny, dependency-free implementation.

Requirements

  • PHP 5.0 or higher

Installation

composer require divengine/enum

Quick start

<?php

require 'vendor/autoload.php';

use divengine\enum;

abstract class Temperature extends enum {}
class HOT extends Temperature {}
class COLD extends Temperature {}

function advise(Temperature $t): string
{
    if ($t instanceof HOT) {
        return 'Drink water';
    }
    return 'Wear a coat';
}

echo advise(new HOT());

Values and comparison

By default, getValue() returns the class name and __toString() uses it. You can set a custom value by defining a public $value on the subclass.

<?php

class HOT extends Temperature
{
    public $value = 'hot';
}

$hot = new HOT();
echo $hot->getValue(); // hot
echo (string) $hot;    // hot

Note about native PHP enums

PHP 8.1+ includes native enums. For new code on modern PHP, prefer native enums. This library can still be useful for older PHP versions or for class-based taxonomies and polymorphism. Integration with native enums is possible via adapters, but not provided by this library.

Docs

See docs/README.md for guides and FAQ.

License

This project is licensed under the GNU General Public License. See LICENSE.