cehmke / php-enum
Simple enum interface allowing both static comparison and instanced interactions
Installs: 1
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/cehmke/php-enum
Requires
- php: >=7.2
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