Re: Typed constants revisited

From: Date: Mon, 28 Mar 2022 12:53:56 +0000
Subject: Re: Typed constants revisited
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-117437@lists.php.net to get a copy of this message
> Constants are not abstract in an interface - they must be assigned a > value. Only classes and methods can be abstract. Within an abstract class > it is not valid to have an abstract property. Properties can be defined > protected int $id; and optionally assigned a value `protected > int $id = > 5;, but cannot be abstract protected int $id;`. > That's the *current* state of the language indeed, but to me, [part of] your proposal looks like introducing "abstract constants"... Maybe I'm misunderstanding? > So to me it makes more sense to have constants follow the same syntax as > properties public const bool CAN_FLY; without the > abstract keyword. > > An example: > > ``` > abstract class Bird > { > public const bool CAN_FLY; > protected bool $isExtinct; > ``` > > This allows for similar behavior, similar requirements, and similar syntax > - consistency ftw! > For similarity/consistency, the $isExtinct property should probably be [public and] static (actually readonly too, but cannot be both). But, again, we can also see some similarity with static *methods*, e.g.: ``` abstract class Bird { abstract public const bool CAN_FLY; abstract public static function isExtinct(): bool; } class Dove extends Bird { // NOTE: the following two lines are required (in the class definition) public const bool CAN_FLY = true; public function static isExtinct(): bool { return false; } } // var_dump(Dove::CAN_FLY); // var_dump(Dove::isExtinct()); ``` Besides, an uninitialized property must be initialized before first read, but is *not* required to be overridden/redefined (with a value) in a child class; so in this example (still hypothetical): ``` abstract class Bird { public const bool CAN_FLY; public static bool $isExtinct; } class Dodo extends Bird { // NOTE: the following two lines are commented out // public const bool CAN_FLY = false; // public static bool $isExtinct = true; } var_dump(Dodo::CAN_FLY); var_dump(Dodo::$isExtinct); ``` where would the [missing value for constant] error be: on the definition of class Dodo (like for an unimplemented abstract method), or only when trying to access Dodo::CAN_FLY (like for an uninitialized property)? > > There seems to be interest and good use cases (thanks Sara for the good > practical example!). At this point I'm going to work on a new RFC with all > the details and feedback from this discussion. > > Thanks & good luck! =) -- Guilliam Xavier

« previous php.internals (#117437) next »