WeSee
WeSee

Reputation: 3762

PHP 8: Enum in class?

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?

Upvotes: 12

Views: 8597

Answers (1)

Raxi
Raxi

Reputation: 2860

You cannot embed the enum within the class; however, in PHP enums are effectively classes, so you can easily merge the class and the enum into one (which is likely what you're looking for)

Consider something like this:

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(); 

Upvotes: 5

Related Questions