Crell / enum-comparison

A comparison of enumerations and similar features in different languages
80 stars 7 forks source link

Static methods #27

Closed iluuu1994 closed 3 years ago

iluuu1994 commented 3 years ago

The RFC says:

Specifically, the following features of objects are not allowed on enumerations: Static methods

Any specific reason this shouldn't be allowed? Also, are we talking about enums or the enum cases?

Example where this would be useful:

enum Foo {
    ...

    public static function fromRepresentation1($value) {
        return match ($value) { ... };
    }

    public static function fromRepresentation2($value) {
        return match ($value) { ... };
    }
}

$foo = Foo::fromRepresentation1(1);
$foo = Foo::fromRepresentation2('foo');
Crell commented 3 years ago

I had intended for both, because I couldn't think of a use case for them. But that's a good one. Should we allow static methods on both, or just on the Enum?

iluuu1994 commented 3 years ago

Should we allow static methods on both, or just on the Enum?

I'd say just on enums, there's no obvious way to invoke them on enum cases (other than through the instance in which case they could just be an instance method in the first place).

Crell commented 3 years ago

Added that, and an example of using a "named constructor" for an enum to demonstrate it.

iluuu1994 commented 3 years ago

Thank you :)