calabrothers/php-ds-enum

1.0.0 2020-01-19 21:20 UTC

This package is auto-updated.

Last update: 2024-10-20 10:14:58 UTC


README

Build Status Coverage Status Total Downloads License

A collection of classes to support Enum data types.

Install

composer require calabrothers/php-ds-enum

Test

composer install
composer test

HowTo

Enum library provides two base classes:

  • Enum
  • EnumUnique

Enum Class

use Ds\Enum;

class MyEnum extends Enum {
    public const FOO            = 0;
    public const BAR            = 0;
}

As C++, Enum allows duplicated values, in this case FOO and BAR. The MyEnum internal representation is integer. You can use both classic object constructor as

$oObj = new MyEnum(0);

or from a factory function:

$oObj = MyEnum::FOO();

or with a copy constructor:

$oObj = new MyEnum(MyEnum::FOO());    

or from a string:

$oObj = MyEnum::fromString('FOO');

then you can use classic comparison operator

echo ($oObj == MyEnum::FOO() ? "Oh yeah" : "uhm"); // Oh yeah

EnumUnique Class

use Ds\Enum;

class MyEnumUnique extends EnumUnique {
    public const FOO            = 0;
    public const BAR            = 1;
}

For this class

$oObj = MyEnumUnique::FOO();
echo ($oObj == MyEnumUnique::FOO() ? "Oh yeah" : "uhm"); // Oh yeah
echo ($oObj == MyEnumUnique::BAR() ? "uhm" : "not bad"); // not bad

Default values

Both base classes support default value. For example, a unique class with default value will be:

use Ds\Enum;

class MyEnumUniqueDef extends EnumUnique {
    public const __DEFAULT__    = 0;
    public const FOO            = 0;
    public const BAR            = 1;
}

then you can also use default constructor:

$oObj = new MyEnumUniqueDef();
echo ($oObj == MyEnumUniqueDef::FOO() ? "Oh yeah" : "uhm"); // Oh yeah

Credits

Support Quality Code

Foo

License

The MIT License (MIT). Please see LICENSE for more information.