Simple and fast implementation of enumerations
In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. — Wikipedia
SplEnum is not integrated to PHP, you have to install it separately:
$ sudo pecl install SPL_Types
.
In addition, it's not a panacea:
class Month extends SplEnum {
const JANUARY = 1;
const FEBRUARY = 2;
}
class Fruit extends SplEnum {
const APPLE = 1;
const ORANGE = 2;
}
// you must create new instance before each use:
$jan = new Month(Month::JANUARY);
$jan2 = new Month(Month::JANUARY);
$apple = new Fruit(Fruit::APPLE);
var_dump($jan === $jan2); // false
var_dump($jan === Month::JANUARY); // false
var_dump($jan == Fruit::APPLE); // true
Enum benchmark on PHP 7
$ tests/benchmark/enum.php 100000
------------------------------- ------------ --------------
Test Memory Avg Duration All
------------------------------- ------------ --------------
Reflection enum 1.52 KiB 1820 ms
Reflection enum (no magic) 1.52 KiB 1718 ms
Explicit enum 0.71 KiB 959 ms
myclabs/php-enum 0.68 KiB 1971 ms
marc-mabe/php-enum 1.59 KiB 2219 ms
marc-mabe/php-enum (no magic) 1.59 KiB 1969 ms
happy-types/enumerable-type 1.81 KiB 2322 ms
------------------------------- ------------ --------------
Set benchmark on PHP 7
$ tests/benchmark/set.php 100000
-------------------- ------------ --------------
Test Memory Avg Duration All
-------------------- ------------ --------------
Reflection set 1.36 KiB 1238 ms
marc-mabe/php-enum 1.59 KiB 2861 ms
-------------------- ------------ --------------
final class Color extends ReflectionEnum implements EnumDefault
{
const RED = 1;
const GREEN = 2;
const BLUE = 3;
/**
* @return Color
*/
public static function byDefault()
{
return self::byValue(self::RED);
}
}