Download the PHP package patchlevel/enum without Composer
On this page you can find all versions of the php package patchlevel/enum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download patchlevel/enum
More information about patchlevel/enum
Files in patchlevel/enum
Package enum
Short Description Small lightweight library to create enum in PHP without SPLEnum and strict comparisons allowed
License MIT
Homepage https://github.com/patchlevel/enum
Informations about the package enum
enum
Small lightweight library to create enum in PHP without SPLEnum and strict comparisons allowed.
dislcaimer
For project that are build on PHP >=8.1 please use the language build in Enums described in this rfc: https://wiki.php.net/rfc/enumerations This library should not be needed anymore and will not support PHP >8.1.
installation
declaration
First of all you have to define your enum.
To do this, you have to inherit from the Enum
class, create a few constants (the value must be unique and a string)
and define methods that return an enum representation.
Here is an example:
self::get()
ensures that exactly one instance of a representation really exists
so that strict comparisons can be used without problems.
Alternatively, you can inherit the ExtendedEnum
, which comes with a few conveniences,
more about this under ExtendedEnum.
api
work with enum
Strict comparisons are not a problem as it ensures that there is only one instance of a certain value.
fromString
You can create an enum from a string. It is checked internally whether the value is valid,
otherwise an InvalidValue
exception is thrown.
toString
The other way around, an enum can also be converted back into a string.
equals
The Equals method is just a wrapper for $a === $b
.
isValid
isValid can be used to check whether the transferred value is valid. The return value is a boolean.
values
You can also get all Enum instances.
keys
Or all keys.
extended enum
Alternatively, it can also extend from ExtendedEnum
.
This implementation also provides other features mostly magic methods:
__toString
, __callStatic
and implementing \JsonSerializable
.
__callStatic
With the magic method __callStatic
it is possible to create an Enum instance based only on the constant names.
So no extra method is needed to be defined. If the constant name doesn't exist in the enum a BadMethodCall
exception is thrown.
__toString
Just the magic method implementation of toString
.
JsonSerializable
The ExtendedEnum already implements the method jsonSerialize
from the interface \JsonSerializable
.
This means that \json_encode
will automatically serialize the value in the right manner.
Beware that \json_decode
won't automatically decode it back into the enum. This job must be tackled
manually. See this example:
All versions of enum with dependencies
ext-json Version ^7.4|^8.0