我有一个仅适用于两种类型a和 的课程b。
我今天的“旧式”代码:
class Work1 {
public function do(string $type):string {
if ($type!="a" && $type!="b")
throw new Error("wrong type");
return "type is $type";
}
}
echo (new Work())->do("a"); // type is a
echo (new Work())->do("c"); // exception: wrong type
Run Code Online (Sandbox Code Playgroud)
现在有了 PHP 8,我们有了enum更好的参数检查选项:
enum WorkType {
case A;
case B;
}
class Work2 {
public function __construct(private WorkType $type) {}
public function do() {
return "type is ".$this->type->name;
}
}
echo (new Work2(WorkType::A))->do(); // type is A
Run Code Online (Sandbox Code Playgroud)
由于 WorkType 和 Work2 不相关,我喜欢将Enum WorkType声明移至类内部Work2。还是语言设计必须将其置于外部?
您不能将枚举嵌入到类中;然而,在 PHP 中,枚举实际上是类,因此您可以轻松地将类和枚举合并为一个(这可能就是您正在寻找的)
考虑这样的事情:
enum Work {
case A;
case B;
public function do() {
return match ($this) {
static::A => 'Doing A',
static::B => 'Doing B',
};
}
}
$x = Work::A;
$x->do();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3750 次 |
| 最近记录: |