php - php中的通用枚举类型

标签 php types enums

如何指定参数类型以采用任何枚举值?

function processEnum(enum $value) 这样的东西是理想的,但是似乎什么都不存在?

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!

此外,最好将支持的与非支持的枚举或其他支持的类型分开;例如,作为字符串支持的枚举。

最佳答案

所有枚举实现the UnitEnum interface和支持的枚举(具有类型和 ->value 属性的枚举)也实现了 the BackedEnum interface .您可以为这些编写类型约束:

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

关于php - php中的通用枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73827043/

相关文章:

php - 告诉 Composer 使用不同的 PHP 版本

haskell - 避免对 Haskell 的原始痴迷

Java 泛型 : Multiple Inheritance in Bounded Type Parameters <T extends A & I>

c# - 可以根据字符串名称加载枚举吗?

python - 为什么 Python 枚举中允许可变值?

java - 多个 if 语句输出不正确

Php Mysql 选择带有关联数组的列

php - OSX本地环境中的Symfony2权限问题

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

types - Lisp 类型的系统故障