Implementation of Enumeration Classes in PHP. The better alternative for Enums.
In contrast to existing solutions, this implementation avoids usage of Magic methods and
Reflection to provide better performance and code autocompletion.
The Enumeration class holds a reference to a single Enum element represented as an object (singleton) to provide the possiblity
to use strict (===
) comparision between the values.
Also, it uses static properties that can utilize the power of Typed Properties.
The Enumeration Classes are much closer to other language implementations like Java Enums
and Python Enums.
A basic way to declare a named Enumeration class:
<?php
use Dbalabka\Enumeration\Enumeration;
final class Action extends Enumeration
{
public static $view;
public static $edit;
}
Action::initialize();
Note! You should always call the Enumeration::initialize()
method right after Enumeration Class declaration.
To avoid manual initialization you can setup the StaticConstructorLoader provided in this library.
Declaration with Typed Properties support:
<?php
final class Day extends Enumeration
{
public static Day $sunday;
public static Day $monday;
public static Day $tuesday;
public static Day $wednesday;
public static Day $thursday;
public static Day $friday;
public static Day $saturday;
}
Day::initialize();
By default an enumeration class does not require the value to be provided. You can use the constructor to set any types of values.
- Flag enum implementation example:
<?php final class Flag extends Enumeration { public static Flag $ok; public static Flag $notOk; public static Flag $unavailable; private int $flagValue; protected function __construct() { $this->flagValue = 1 << $this->ordinal(); } public function getFlagValue() : int { return $this->flagValue; } }
- You should override
initializeValues()
method to set custom values for each Enum element.<?php final class Planet extends Enumeration { public static Planet $mercury; public static Planet $venus; public static Planet $earth; public static Planet $mars; public static Planet $jupiter; public static Planet $saturn; public static Planet $uranus; public static Planet $neptune; private float $mass; // in kilograms private float $radius; // in meters // universal gravitational constant (m3 kg-1 s-2) private const G = 6.67300E-11; protected function __construct(float $mass, float $radius) { $this->mass = $mass; $this->radius = $radius; } protected static function initializeValues() : void { self::$mercury = new self(3.303e+23, 2.4397e6); self::$venus = new self(4.869e+24, 6.0518e6); self::$earth = new self(5.976e+24, 6.37814e6); self::$mars = new self(6.421e+23, 3.3972e6); self::$jupiter = new self(1.9e+27, 7.1492e7); self::$saturn = new self(5.688e+26, 6.0268e7); self::$uranus = new self(8.686e+25, 2.5559e7); self::$neptune = new self(1.024e+26, 2.4746e7); } public function surfaceGravity() : float { return self::G * $this->mass / ($this->radius * $this->radius); } public function surfaceWeight(float $otherMass) { return $otherMass * $this->surfaceGravity(); } }
Declaration rules that the developer should follow:
- The resulting Enumeration class should be marked as
final
. Abstract classes should be used to share functionality between multiple Enumeration classes....Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations... (from Python Enum documentation)
- Constructor should always be declared as non-public (
private
orprotected
) to avoid unwanted class instantiation. - Implementation is based on assumption that all class static properties are elements of Enum.
- The method
Dbalabka\Enumeration\Enumeration::initialize()
should be called after each Enumeration class declaration. Please use the StaticConstructorLoader provided in this library to avoid boilerplate code.
<?php
use Dbalabka\Enumeration\Examples\Enum\Action;
$viewAction = Action::$view;
// it is possible to compare Enum elements
assert($viewAction === Action::$view);
// you can get Enum element by name
$editAction = Action::valueOf('edit');
assert($editAction === Action::$edit);
// iterate over all Enum elements
foreach (Action::values() as $name => $action) {
assert($action instanceof Action);
assert($name === (string) $action);
assert($name === $action->name());
}
PHP 8 is going to support match expression which simplifies usage of enums:
<?php
use Dbalabka\Enumeration\Examples\Enum\Action;
$action = Action::$view;
echo match ($action) {
Action::$view => 'View action',
Action::$edit => 'Edit action',
}
- Static constructor usage
- Option enum similar to Rust enum
- Shape enum similar to Rust enum
- Serialization restriction
- Day enum
- Flag enum
- Planet enum
In the current implementation, static property value can be occasionally replaced. Readonly Properties is aimed to solve this issue. In an ideal world Enum values should be declared as a constants. Unfortunately, it is not possible in PHP right now.
<?php
// It is possible but don't do it
Action::$view = Action::$edit;
// Following isn't possible in PHP 7.4 with declared properties types
Action::$view = null;
Also, see most recent Write-Once Properties RFC that aimed to address this issue.
This implementation relies on class static initialization which was proposed in Static Class Constructor. The RFC is still in Draft status but it describes possible workarounds. The simplest way is to call the initialization method right after the class declaration, but it requires the developer to keep this in mind. Thanks to Typed Properties we can control uninitialized properties - PHP will throw an error in case of access to an uninitialized property. It might be automated with custom autoloader Dbalabka\StaticConstructorLoader\StaticConstructorLoader provided in this library:
<?php
use Dbalabka\StaticConstructorLoader\StaticConstructorLoader;
$composer = require_once(__DIR__ . '/vendor/autoload.php');
$loader = new StaticConstructorLoader($composer);
Also, it would be very helpful to have expression based properties initialization (see C# example):
class Enum {
// this is not allowed
public static $FOO = new Enum();
public static $BAR = new Enum();
}
See examples/class_static_construct.php for example.
There is no possibility to serialize the singleton. As a result, we have to restrict direct Enum object serialization.
<?php
// The following line will throw an exception
serialize(Action::$view);
New custom object serialization mechanism does not help with singleton serialization
but it gives the possibility to control this in the class which holds the references to Enum instances. Also, it can be worked around
with Serializable Interface in a similar way.
For example, Java handles Enums serialization differently than other classes, but you can serialize it directly thanks to readResolve().
In PHP, we can't serialize Enums directly, but we can handle Enums serialization in class that holds the reference. We can serialize the name of the Enum constant and use valueOf()
method to obtain the Enum constant value during unserialization.
So this problem somewhat resolved the cost of a worse developer experience. Hope it will be solved in future RFCs.
class SomeClass
{
public Action $action;
public function __serialize()
{
return ['action' => $this->action->name()];
}
public function __unserialize($payload)
{
$this->action = Action::valueOf($payload['action']);
}
}
See complete example in examples/serialization_php74.php.
Unfortunately, it is not easy to use callable that is stored in static property. There was a syntax change since PHP 7.0 which complicates the way to call callable.
// Instead of using syntax
Option::$some('1'); // this line will rise an error "Function name must be a string"
// you should use
(Option::$some)('1');
It is the main disatvatige of static class properties.
It can be workarounded by magic calls using __callStatic
but such option suffers from missing autosuggestion,
negative performance impact and missing static analysis.
Option::some('1');
It would be helpful to have PHP built-in suppoort for late (in runtime) constants initialization or/and class constants initialization using simple expressions:
class Enum {
// this is not allowed
public const FOO = new Enum();
public const BAR = new Enum();
}
Still, calling Enum::FOO()
will try to find a method instead of trying to treat constant's value as a callable. We assume, that such PHP behavior can be improved.
Libraries:
- https://github.com/myclabs/php-enum (~1200 stars)
- https://github.com/BenSampo/laravel-enum (~700 stars)
- https://github.com/marc-mabe/php-enum (~300 stars)
- https://github.com/spatie/enum (~200 stars)
- https://github.com/Elao/PhpEnums (~100 stars)
- https://github.com/consistence/consistence#enums-and-multienums (~100 stars)
- https://github.com/mad-web/laravel-enum (~80 stars)
- https://github.com/greg0ire/enum (~40 stars)
- https://github.com/grifart/enum
- https://github.com/zlikavac32/php-enum
PHP native:
(there are a lot of other PHP implementations)
- Enum Types - The Java™ Tutorials
- Enum — Support for enumerations - The Python Standard Library
- Class Enum<E extends Enum> - Java™ Platform, Standard Edition 7 API Specification
- Use enumeration classes instead of enum types - .NET microservices - Architecture e-book
- Enumeration Class implementation - Microservices Architecture and Containers based Reference Application
- Python Enum is a singleton
- Java Enum is a singleton