How to check if enum type?
Asked Answered
R

4

24

How can I tell if a variable is of type enum?

I have installed PHP 8.1 on my Ubuntu 20.04. I'm testing the new "enum" types.

Is something like that possible?

is_enum($var)
gettype($var) === 'enum'
Rimini answered 5/12, 2021 at 17:57 Comment(0)
R
56

Someone told me the solution:

if ($var instanceof \UnitEnum) {
   echo 'is enum';
}
Rimini answered 6/12, 2021 at 19:12 Comment(4)
php.net/manual/en/class.unitenumGasparo
Or depending on your needs, instanceof BackedEnum.Eyeopener
this always returns false for meQuotidian
instanceof \IntBackedEnum if you're using an enum with an integer return typeFoolhardy
R
18

use enum_exists, for check if is a enum.

if (enum_exists(Item::class)) {
    $myType = Item::Manufactured;
}
Reliable answered 5/12, 2021 at 18:11 Comment(2)
It also works with enum_exists($var::class)Pendulous
Note that this also tries to autoload by default (second parameter): php.net/manual/en/function.enum-exists.phpTymon
V
3

To check if a $var is a BackedEnum, you can use this code:

if ($var instanceof \BackedEnum) {
   echo 'is a backed enum';
}

Read more on documentation of PHP about BackedEnum.

Visceral answered 7/10, 2023 at 15:53 Comment(0)
D
2

You also can check it through reflection:

var_dump(
    (new ReflectionClass($object::class))
        ->isEnum()
);
Doublereed answered 27/4, 2023 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.