2017 © Pedro Peláez
 

library phpenums

An experimental Enum implementation for PHP7

image

bonndan/phpenums

An experimental Enum implementation for PHP7

  • Sunday, January 29, 2017
  • by bonndan
  • Repository
  • 0 Watchers
  • 0 Stars
  • 8 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

PHP Enums

Build Status Minimum PHP Version, (*1)

Yet another implementation of Enums in PHP. The difference to most other implementations is that the implemetation is very close to Java. Static properties are used, but like in Java they are real instances of the Enum providing all methods etc:, (*2)


class Fruit extends \Pava\Enum { /** * @var Fruit */ public static $APPLE; /** * @var Fruit */ public static $BANANA; }

So you can use static typing:


$mix = function (Fruit $a, Fruit $b) {}; $blend = $mix(Fruit::$APPLE, Fruit::$BANANA); $grow = function () : Fruit { return Fruit::$APPLE }; assert(Fruit::$APPLE instanceof Fruit);

What are the drawbacks?

  • Each enum has to be registered (unless static constructors arrive in PHP). The reason is that static properties can only have scalar values as default.

//class Fruit ... Pava\register(Fruit::class);
  • You need to annotate all static props in order to get your IDE working with it, but at least this works.
  • No default values usable. At "compile time" $BANANA is not yet an instance. However you can use null as default value.

//not possible $a = function (Fruit $a = Fruit::$BANANA) {};
  • Use/import is not possible, i.e. you cannot just write $BANANA.

Advanced use

Each enum instance can obtain its own properties by implementing the magic invoke method., (*3)


class Fruit extends \Pava\Enum { private $color; /** * @var Fruit */ public static $APPLE; /** * @var Fruit */ public static $BANANA; public function color() : string { return $this->color; } public function __invoke() { if ($this->name() == 'BANANA') $this->color = 'yellow'; if ($this->name() == 'APPLE') $this->color = 'green'; } } Pava\register(Fruit::class); echo 'The apple is ' . Fruit::$APPLE->color();

The Versions

29/01 2017

dev-master

9999999-dev

An experimental Enum implementation for PHP7

  Sources   Download

MIT

The Requires

  • php ^7

 

The Development Requires

27/01 2017

0.1.0

0.1.0.0

An experimental Enum implementation for PHP7

  Sources   Download

The Requires

  • php ^7

 

The Development Requires