rfc:enum_allow_static_properties

This is an old revision of the document!


PHP RFC: Allow static properties in enums

Introduction

Although enums are immutable objects, it is often useful to have functions or methods that operate on enum instances. In many cases, it would make sense to declare that functionality as static methods on the enum itself. In cases where static methods require shared state, it would be useful to allow storing those shared state in static properties. To ensure immutability of enum instances, it's only necessary to forbid instance properties, but all properties were forbidden in the initial functionality included with the enums RFC.

Proposal

Allow static properties to be declared on enums or to be inherited by using traits. Continue to forbid instance properties. Additionally, update error messages to mention that only instance properties are forbidden on enums.

This is useful in cases where shared state involving immutable instances is used, e.g.

enum Environment {
    case DEV;
    case STAGE;
    case PROD;
 
    private static Environment $currentEnvironment;
 
    /**
     * Read the current environment from a file on disk, once.
     * This will affect various parts of the application.
     */
    public static function current(): Environment {
        if (!isset(self::$currentEnvironment)) {
            $info = json_decode(file_get_contents(__DIR__ . '/../../config.json'));
            self::$currentEnvironment = match($info['env']) {
                'dev' => self::DEV,
                'stage' => self::STAGE,
                'prod' => self::PROD,
            };
        }
        return self::$currentEnvironment;
    }
    // Other methods can also access self::$currentEnvironment
}
printf("Current environment is %s\n", Environment::current()->name);

Compared to alternatives such as global variables and local static variables, this is a useful option to have for the following reasons:

  1. Property types can be used.
  2. Visibility is easier to enforce.
  3. It is easier to reset static properties in unit tests.
  4. This can result in more concise and easier to understand code.

This is also useful because it allows enums to use traits that contain static properties, which was previously a fatal error.

Backward Incompatible Changes

None

Proposed PHP Version(s)

8.1

RFC Impact

To SAPIs

None

To Opcache

None

Unaffected PHP Functionality

Instance properties continue to be forbidden on enums.

Proposed Voting Choices

Yes/No, requiring a 2/3 majority

References

https://externals.io/message/112626#113037 brought up the same suggestion.

enums RFC

rfc/enum_allow_static_properties.1621260128.txt.gz · Last modified: 2021/05/17 14:02 by tandre