This RFC proposes to add a built-in Enumeration to PHP to specify the possible return values of sorting/comparison functions. This enumeration would be easier for developers to use than the existing magic constants, although support for those remains.
This RFC includes two changes, specifically.
One, the following Enumeration is defined in PHP's standard library.
enum Ordering { case LeftGreater; case RightGreater; case Equal; case Uncomparable; }
Second, all sorting and comparison functions that accept a user-supplied comparison function (usort()
, uksort()
, etc.) are modified to allow the developer to return either an integer (as now) or an instance of Ordering
. The semantic meaning of the enum cases is equivalent to their integer versions.
The primary benefit of this change is usability. It is very easy to forget which of 1 and -1 mean which sorting direction (one of the RFC authors has to look it up every single time), whereas a closed set of values naturally maps to an enumeration. An enumeration with named options is considerably more self-documenting.
PHP currently has no explicit way to indicate that two parameters are simply not logically comparable. In practice it rarely comes up (as most developers will only try sorting values that are in facts sortable), but it is a gap in the current design. However, the User Defined Operator Overloads RFC, should it pass, would present additional cases where incompariable objects are compared.
PHP's current implicit mechanism is to return 1 when two values are uncomparable, regardless of which comes first. That is highly subtle and not well known, as well as logically suspect. Providing an explicit “this is not logical” return value is, as above, more self-documenting, more obvious to use, and offers the potential for slightly improved error handling in the engine.
The global namespace symbol “Ordering” is now taken.
PHP 8.2
The specific case names are subject to inevitable bikeshedding.
This RFC very specifically does not remove or deprecate the existing integer returns for comparison functions. Those will continue to work exactly as now. Whether or not they should be removed in PHP 9 or 10 is a question for another time.
This is a simple yes/no vote, requiring 2/3 to pass.
Pending...
After the project is implemented, this section should contain
Links to external references, discussions or RFCs
Keep this updated with features that were discussed on the mail lists.