Skip to content
Advertisement

Generic enum type in php

How can I specify an argument type to take any enum value?

Something like function processEnum(enum $value) would be ideal, however nothing seems to exist?

enum Numbers: int {
  case FIRST = 1;
  case SECOND = 2;
}


enum Foo: string {
  case BAR = 'bar';
}

function printEnum($enumValue) {
  echo $enumValue->value;
}

printEnum(Numbers::FIRST); // 1
printEnum(Foo::BAR); // 'bar'
printEnum('fail'); // I want to reject this!

Additionally it would be nice to separate backed vs non-backed enums or additionally backed types; enums that are backed as strings for example.

Advertisement

Answer

All enums implement the UnitEnum interface, and backed enums (those with a type and a ->value property) also implement the BackedEnum interface. You can write type constraints for those:

enum Numbers: int {
  case FIRST = 1;
  case SECOND = 2;
}
enum Foo: string {
  case BAR = 'bar';
}
enum Something {
   case WHATEVER;
}

function doSomething(UnitEnum $enumValue) {
  echo "blahn";
}
function printEnum(BackedEnum $enumValue) {
  echo $enumValue->value, "n";
}

doSomething(Numbers::FIRST); // blah
doSomething(Foo::BAR); // blah
doSomething(Something::WHATEVER); // blah
doSomething('fail'); // TypeError

printEnum(Numbers::FIRST); // 1
printEnum(Foo::BAR); // 'bar'
printEnum(Something::WHATEVER); // TypeError
printEnum('fail'); // TypeError
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement