gpslab / enum
Simple and fast implementation of enumerations
dev-master
2019-12-19 07:53 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- happy-types/enumerable-type: ~1.0
- marc-mabe/php-enum: ~2.3
- myclabs/php-enum: ~1.5
- php-coveralls/php-coveralls: ^1.0
- phpbench/phpbench: ~0.12
- phpunit/phpunit: ^4.8.36
- scrutinizer/ocular: ~1.3
- symfony/console: ~2.3|~3.0
This package is auto-updated.
Last update: 2024-10-19 19:00:59 UTC
README
PHP enum
Simple and fast implementation of enumerations
Introduction
Definition
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
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
Benchmark
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
-------------------- ------------ --------------
How to get enum with default value?
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); } }