php-src icon indicating copy to clipboard operation
php-src copied to clipboard

enums

Open ghost opened this issue 4 years ago • 4 comments

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?

ghost avatar Dec 07 '21 10:12 ghost

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

iluuu1994 avatar Dec 07 '21 10:12 iluuu1994

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!

ghost avatar Dec 07 '21 10:12 ghost

There's also name.

echo Foo::Bar->name;

https://www.php.net/manual/en/language.enumerations.basics.php

iluuu1994 avatar Dec 07 '21 10:12 iluuu1994

Thank you!

ghost avatar Dec 07 '21 10:12 ghost