Simple Backed Enums implementation for PHP <8.1
composer require hyqo/enum
This is very similar to real PHP 8.1 Backed Enums: https://www.php.net/manual/en/language.enumerations.backed.php
static
methodfrom($case): self
will take a scalar and return the corresponding Enum Case. If one is not found, it will throw an exceptionstatic
methodtryFrom($case): ?self
will take a scalar and return the corresponding Enum Case. If one is not found, it will returnnull
static
methodcases(): array
returns a packed array of all defined Cases- read-only property
value
is the value specified in the definition - read-only property
name
is the case-sensitive name of the case itself - Enums may contain methods
But these are not real Enums, so Cases must be defined via public constants
use \Hyqo\Enum\Enum;
class Suit extends Enum
{
public const Hearts = 'H';
public const Diamonds = 'D';
public const Clubs = 'C';
public const Spades = 'S';
public function color(): string
{
switch ($this->value) {
case self::Hearts:
case self::Diamonds:
return 'red';
case self::Clubs:
case self::Spades:
return 'black';
}
}
}
Suit::from(Suit::Hearts)->value; //H
Suit::from(Suit::Hearts)->name; //Hearts
Suit::from(Suit::Hearts)->color(); //red
Suit::Spades()->value; //S
Suit::Spades()->name; //Spades
Suit::Spades()->color(); //black
Suit::tryFrom('foo'); //null
Suit::from('foo'); //throw \Hyqo\Enum\InvalidValueException
Suit::from(Suit::Hearts)->foo; //throw \RuntimeException
Suit::from(Suit::Hearts)->value = 'foo'; //throw \RuntimeException