Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading