如何指定参数类型以采用任何枚举值?
像 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/