Re: RFC: autoconst
| From: | Serhii Smirnov | Date: | Sun, 01 Aug 2021 15:59:39 +0000 |
| Subject: | Re: RFC: autoconst | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-115620@lists.php.net to get a copy of this message | ||
> 1 авг. 2021 г., в 17:08, Rowan Tommins <rowan.collins@gmail.com> написал(а):
>
> On 01/08/2021 12:21, Serhii Smirnov wrote:
>> instead of defining constants like:
>> const FOO = 'FOO';
>>
>> they could be defined like:
>> autoconst FOO; // defines a constant FOO with the value 'FOO'
>
>
> While I've certainly seen constants like this in the past, I think they mostly fall into
> two categories:
>
> A) Constants where the value doesn't actually matter, and you just need something to
> compare input against. As of PHP 8.1, we will have enums, where you can just write "case
> FOO;" and not assign any value at all, which can probably be used in most of these situations.
>
> B) Constants where the value matters, but the constant name isn't actually conveying
> anything. Given your suggestion of built-in transforms for lower-case etc, these seem like what
> you're interested in.
>
> These often arise from a misunderstanding of the dogma to "avoid magic numbers and
> hard-coded values", and result in code that looks like it's SHOUTING without conveying any
> extra information. For instance, people start with this:
I was more interested in autoconst keyword that reduces copy/pasting constant name as it's
value. camelcase and snakecase is an addition. A real example why I wanted to use autoconst: on the
past project, we had class that holds constants with the feature flag names. Something like:
class Features
{
const FEATURE_FLAG_WITH_SOME_LONG_NAME = 'feature_flag_with_some_long_name';
const FEATURE_SOME_ANOTHER_COOL_FEATURE = 'feature_some_another_cool_feature';
}
later, in the code we had to check if certain feature is enabled in the system:
if ($featureManager->isEnabled(Features::FEATURE_FLAG_WITH_SOME_LONG_NAME)) {
// some feature related code goes here
}
The class Features could be written as:
class Features
{
autoconst lower FEATURE_FLAG_WITH_SOME_LONG_NAME, FEATURE_SOME_ANOTHER_COOL_FEATURE;
}