0

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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.