PHP 7.1 enum implementation
It is a well known fact that PHP is missing a basic enum type, ignoring the rather incomplete SplEnum implementation
which is only available as a PECL extension. There are also quite a few other userland enum implementations around,
but all of them have one or another compromise. This library tries to close that gap as far as PHP allows it to.
At its core, there is the DASPRiD\Enum\AbstractEnum class, which by default will work with constants like any other
enum implementation you might know. The first clear difference is that you should define all the constants as protected
(so nobody outside your class can read them but the AbstractEnum can still do so). The other even mightier difference
is that, for simple enums, the value of the constant doesn't matter at all. Let's have a look at a simple example:
use DASPRiD\Enum\AbstractEnum;
/**
* @method static self MONDAY()
* @method static self TUESDAY()
* @method static self WEDNESDAY()
* @method static self THURSDAY()
* @method static self FRIDAY()
* @method static self SATURDAY()
* @method static self SUNDAY()
*/
final class WeekDay extends AbstractEnum
{
protected const MONDAY = null;
protected const TUESDAY = null;
protected const WEDNESDAY = null;
protected const THURSDAY = null;
protected const FRIDAY = null;
protected const SATURDAY = null;
protected const SUNDAY = null;
}If you need to provide constants for either internal use or public use, you can mark them as either private or public, in which case they will be ignored by the enum, which only considers protected constants as valid values. As you can see, we specifically defined the generated magic methods in a class level doc block, so anyone using this class will automatically have proper auto-completion in their IDE. Now since you have defined the enum, you can simply use it like that:
…Of course, all enums are singletons, which are not cloneable or serializable. Thus you can be sure that there is always just one instance of the same type. Of course, the values of constants are not completely useless, let's have a look at a more complex example:
…No open issues yet, or sync has not completed.