I have the following code:
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$enumClass = '\Suit';
$hearts = $enumClass::from('\Suit::Hearts');
var_dump($hearts);
Which results in
PHP Fatal error: Uncaught ValueError: "\Suit::Hearts" is not a valid backing value for enum "Suit"
How can I cast human-readable enum strings such as EnumName::enumCase into BackedEnum?
Is there some way to call some get_enum_from_fqcn('\Namespace\Some\Enum::EnumCase') ?
asked Apr 10, 2022 at 21:20
michnovka
3,4773 gold badges34 silver badges71 bronze badges
1 Answer 1
Just in case someone still needs an answer with this. The value that is supposed to go in from is 'H'
$hearts = Suit::from('H');
If you want it based on the name you could use https://github.com/henzeb/enumhancer, as it allows you to do just that.
enum Suit: string
{
use EnumHancer;
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
And then you can just do:
Suite::make('Hearts');
This will also be helpful with UnitEnums, as you won't be needing values to do it.
answered May 31, 2022 at 18:54
SomeOne_1
1,06813 silver badges12 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php