Hi

On 3/29/23 12:41, Christian Schneider wrote:
And to give a specific example from PHP 8.3: As part of the Randomizer additions RFC 
(https://wiki.php.net/rfc/randomizer_additions), PHP 8.3 got its first "natively 
included" enum (\Random\IntervalBoundary). This enum works together with the new 
Randomizer::getFloat() method to specify if the given min and max value may be returned 
or not.

The Randomizer::getFloat() method internally includes switch statement that 
chooses the implementation based on the IntervalBoundary value given.

If a user would be able to extend the IntervalBoundary enum, the method would 
not be able to make sense of it.

The IntervalBoundary enum completely enumerates all four possible combinations 
for the two possible states for each of the two boundaries (2*2 = 4). By 
definition there is no other valid value.

I do understand the reason behind making Enums final and your example 
illustrates the point very well.

I still have a question I already asked in a different context: If there ever 
is the need to add a case to an Enum, was there any thought put into making 
this possible? Or is this categorically ruled out when using Enums?

Adding a case to an enum would certainly be considered a breaking change for folks that rely on having exhaustively handled all possible cases.

Let’s look at a very, very hypothetical example: Imagine a Randomizer is much, 
much slower for certain boundaries and it is decided that some programs do not 
care about Closed/Open but instead care more about speed. So they would want to 
use something like IntervalBoundary::Fastest.

In this specific hypothetical example, the fastest case would be one of the existing 4 cases - an alias if you want to call it that.

Defining an alias is possible without breaking compatibility by leveraging class constants:

    <?php

    enum IntervalBoundary {
        case ClosedOpen;
        case ClosedClosed;
        case OpenClosed;
        case OpenOpen;

        public const Fastest = self::ClosedOpen;
    }

    var_dump(IntervalBoundary::ClosedOpen === IntervalBoundary::Fastest);

    function foo(IntervalBoundary $b) {
        var_dump($b);
    }

    foo(IntervalBoundary::Fastest);

-> https://3v4l.org/tT0Ho

Alternatively a method "public static function getFastest(): self" would be possible.

As far as I understand such an addition would *never* be possible, right? This 
means people defining Enums have to be very very certain that no one will ever 
want another value, right?


I believe the short answer to the last question is "Yes".

Best regards
Tim Düsterhus

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

Reply via email to