I have the below sample code:
<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$enumClass = '\Suit';
$hearts = $enumClass::from('H');
var_dump($hearts);
it produces output
enum(Suit::Hearts)
which is desired. However, is there a way to do this using some function calls and not dynamic $enumClass::from('H');
? Such as get_enum($enumClass)::from('H')
or like that?
CodePudding user response:
PHP enumerations are objects and can be determined by autoloading. So if your variable only contains the name of the enumeration, you can first check if the enumeration exists and then use BackedEnum::tryFrom()
or BackedEnum::from()
to get it.
<?php
declare(strict_types=1);
namespace Marcel\Enums;
enum Status: string
{
case Active = 'active';
case Retired = 'retired';
}
$fqcn = Status::class;
$enum = null;
$value = 'active';
if (enum_exists($fqcn)) {
$enum = $fqcn::from($value);
}
There is no additional functionality to get the object first and then execute some method of the object. You can get the fully qualified classname by get_class()
and check in a next step, if the class (enum) exists and as a last step call the BackedEnum::from()
method.