20

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'
0

3 Answers 3

44

Someone told me the solution:

if ($var instanceof \UnitEnum) {
   echo 'is enum';
}
3
13

use enum_exists, for check if is a enum.

if (enum_exists(Item::class)) {
    $myType = Item::Manufactured;
}
2
0

You also can check it through reflection:

var_dump(
    (new ReflectionClass($object::class))
        ->isEnum()
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.