I have a class that works on only the two types a
and b
.
My "oldstyle" code today:
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
Now with PHP 8 we have enum
and better argument checking options:
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
Since WorkType and Work2 are unrelated I like to move the Enum WorkType
declaration to inside the class Work2
. Or does it have to be outside by language design?