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:

echo "Hello, " . $name ?? "World";

And think that they can "avoid hard-coding" like this:

private const HELLO='Hello, ';
private const WORLD='World';
// ...
echo self::HELLO . $name ?? self::WORLD;

But these constants aren't actually doing anything useful - the code is harder to read not easier, and it would be very odd to later change the value of "const WORLD" without also changing its name.

In order to actually be useful, the name of the constant needs to convey something other than its value, like this:

private const MESSAGE_GREETING='Hello, ';
private const MESSAGE_DEFAULT_NAME='World';
// ...
echo self::MESSAGE_GREETING . $name ?? self::MESSAGE_DEFAULT_NAME;


I think if you eliminate constants which can now be enums, and fix constants which are badly named, there won't be enough uses left for this new feature to justify its inclusion in the language.


Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to