Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 8: Enum in class?

Tags:

php

php-8

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?

like image 357
WeSee Avatar asked Mar 17 '26 06:03

WeSee


1 Answers

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(); 
like image 142
Raxi Avatar answered Mar 18 '26 20:03

Raxi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!