12

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?

1
  • 2
    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. Commented Jan 17, 2023 at 11:18

1 Answer 1

6

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(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Do enums have the same behaviour as that of a class?
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 : 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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.