I´m trying to create an php 8.1 enum from a dynamic name. Seems not to be possible. So given an enum
enum Foo {
case bar;
}
The following works of course: Foo::bar While this doesn´t:
$name = "bar";
Foo::${$name}
This results in: Access to undeclared static property App\Console\Commands\Foo::$bar
I tried various tricks here, to no avail. It seems not to be possible to get an enum instance from a dynamic name. My custom and quick workaround looks like this, a static factory:
/**
* @throws \Exception
*/
public static function fromName(string $name) : self {
foreach(Foo::cases() as $enum){
if($enum->name === $name){
return $enum;
}
}
throw new \Exception("Not a valid enum name");
}
I could put this in a trait and inherit this in all my enums, yes, problem solved.
My question is: am I missing something here? Is it really not possible to instantiate an enum with native php methods? Or am I thinking in the wrong direction?
The pre php8.1 class-as-enum composer packages used to have those convenience methods, see https://github.com/bensampo/laravel-enum So why is this pretty common case not part of the specification (just curious)?
foreach(Foo::cases() as $enum)to thisforeach(static::cases() as $enum)so it will be more universal for your multiple enums.