I'm looking at enum in PHP 8.1. I have a string variable gathered from a database record, and I want to select the correct enum value case based on that string. For example:
enum Test: string {
case FOO = 'baz';
case BAR = 'buz';
}
I can select the first of those using the string value of the case:
$x = 'baz';
$y = Test::from($x);
// $y is now `Test::FOO`.
But what about the other way around? What if $x = "FOO"? How do I select the enum case from "FOO"?
Hard-coded, it would be Test::FOO, but I don't know the syntax for using a variable. I've tried a few things like Test::{$x} but the enum syntax doesn't seem to like variables very much.
The standard example all the tutorials give seems a perfect use case for this usage, but none of them mention it.
enum Suit: string {
case Clubs = '♣';
case Diamonds = '♦';
case Hearts = '♥';
case Spades = '♠';
}
I can totally imagine needing to get ♣ from "Clubs". I can't imagine ever needing the reverse.