PHP 8.6: New SortDirection Enum

Version8.6
TypeNew Feature

PHP 8.6 introduces a new Enum called SortDirection in the global namespace, that can be used by core functions and user-land PHP applications as simple, always-available Enum.

The new SortDirection Enum is a Unit Enum, which means the individual elements of the Enum do not have a scalar value such as ASC or DESC backing them. PHP applications can infer the corresponding domain-specific scalar values for the Enum elements.

New SortDirection Enum

enum SortDirection {
    case Ascending;
    case Descending;
}

The declaration is intentionally simple, and, the individual Enum cases do not hold a string or int backed value so the domain-specific backed values can be inferred at the system boundary.

The Enum is declared in the global namespace.

Usage Examples

PHP applications that need to use the new SortDirection Enum can define it as a type. When a backed value is needed, consider using a match expression:

class QueryBuilder {

    private SortDirection $sort;

    public function setSort(SortDirection $sort): void {
        $this->sort = $sort;
    }

    private function getSortKeyword(): string {
        return match($this->sort) {
            SortDirection::Ascending => 'ASC',
            SortDirection::Descending => 'DESC',
        };
    }
}

Functions that validate a sort direction can now rely on the new SortDirection Enum to enforce this through the type system:

- function myCustomSort(string $direction): void {
+ function myCustomSort(SortDirection $direction): void {
-   if ($direction !== 'ASC' && $direction !== 'DESC') {
-       throw new \InvalidArgumentException('$direction must be either ASC or DESC');
-   }
+ // No further validation necessary.
}

Backward Compatibility Impact

SortDirection is a new Enum declared in the global namespace. Unless a PHP application already declares a SortDirection class or an Enum, this change has no backward-compatibility impact.

PHP applications running on PHP 8.1 (the minimum PHP version to support Enums) or later can trivially polyfill this Enum:

if (!enum_exists('SortDirection')) {
    enum SortDirection {
        case Ascending;
        case Descending;
    }
}

SortDirection RFC Discussion Implementation