7

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?

WeSee
  • 3,158
  • 2
  • 30
  • 58
  • 1
    Unlike other languages (Java comes to my mind), PHP classes and enums are always standalone entities that can't be nested. The only mitigation I can think of is to have them added to one same namespace. – Álvaro González Jan 17 '23 at 11:18

1 Answers1

3

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(); 
Raxi
  • 2,452
  • 1
  • 6
  • 10
  • Do enums have the same behaviour as that of a class? – nice_dev Jan 17 '23 at 11:31
  • Great idea! Unfortunately this is no way to go for me since I do have additional properties in my class 'Work` and properties are not supported in `enum` – WeSee Jan 17 '23 at 11:43
  • 1
    @WeSee : ah yes, in that case this solution won't work for you. What is the reason you want to integrate the 2 items ? is it purely cosmetic ? Not that that is a bad reason. I imagine you're already aware, but you can generally use namespaces to divide or group related entities in your codebase. – Raxi Jan 17 '23 at 11:50
  • 2
    @nice_dev : Yes, as far as i'm aware that is largely true. The enum syntax, for a large part, seems to be alternative syntax for constructing a class. They can have methods (where `$this` refers to the specific enum variant) and static methods (specific to the enum type, not any particular variant) and so forth. But of course there are limitations, as WeSee already demonstrated. – Raxi Jan 17 '23 at 11:57