Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic enum type in php

Tags:

types

php

enums

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.

like image 459
Ben Rowe Avatar asked Jul 30 '26 21:07

Ben Rowe


1 Answers

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 "blah\n";
}
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
like image 195
IMSoP Avatar answered Aug 02 '26 10:08

IMSoP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!