cehmke/php-enum

This package is abandoned and no longer maintained. No replacement package was suggested.

Simple enum interface allowing both static comparison and instanced interactions

dev-master 2020-06-10 08:35 UTC

This package is auto-updated.

Last update: 2021-04-10 10:30:53 UTC


README

Provides a simple to use interface to create enums in PHP which allows both static comparisons and instanced interactions.

Installation

composer require cehmke/php-enum

Usage

Create a new class extending cehmke/enum and declare some constants. That's it.

<?php

use Cehmke/Enum;

class Colour extends Enum
{
    public const RED = 'red';
    public const BLUE = 'blue;
    public const GREEN = 'green';
}

The underlying enum class uses reflection to pull the declared constants and use them in a more traditional enum context. so you can easily create a new instance of the enum as follows:

$colour = new Colour(Colour::RED);

This will create a new instance of the enum holding the value of red.

Static functions

contains : returns whether the enum containst the given element.
Colour::contains('red') > true
Colour::contains('orange') > false

elements : returns an array of the elements available to the enum.
Colour::elements() > ['red', 'blue', 'green']

Instance functions

You can then create an instance of the enum like: $colour = new Colour(Colour::RED)
Note: an instance must be initialized with a valid value

get : returns the value of the instance.
$colour->get() > 'red'

set : sets a new value on the instance.
$colour->set(Colour::BLUE) > $colour is now set to 'blue'

is : performs a truth comparison on the instance.
$colour->is('blue') > true
$colour->is('orange') > false

in : returns whether the instance value is found on an array.
$colour->in(['red', 'green']) > false