enums
Description
Hello!
There seems to be no way to get the string representation of an instance of an enum, except with var_export()
enum Foo: string {
case Bar = 'bar';
case Baz = 'baz';
}
$bar = Foo::Bar;
$bar_string = var_export($bar, true);
Also, what if I want to find out the backing value of an enum variable?
$backing_value = (new \ReflectionEnumBackedCase($bar, ???))->getBackingValue();
Any ideas?
That would be the value property.
https://3v4l.org/kIdJu#v8.1rc3
$bar = Foo::Bar;
var_dump($bar->value);
You can read more about backed enums in the documentation. https://www.php.net/manual/en/language.enumerations.backed.php
Thank you very much for your answer @iluuu1994!
In the first point I was referring to obtaining the name of the case, not its backing value.
enum Foo: string {
case Bar = 'qux';
case Baz = 'quux';
}
$foo = Foo::Bar;
// how can I get the string 'Bar' without using var_export()?
Thank you!
There's also name.
echo Foo::Bar->name;
https://www.php.net/manual/en/language.enumerations.basics.php
Thank you!