Use PHP 8.1 Enums, Readonly Properties, and Intersection Types in WordPress Plugins

PHP 8.1 enums, readonly properties and intersection types in a WordPress plugin

PHP 8.1 brought three features that make plugin code stricter with little effort. Enums replace groups of string constants, so an invalid status is a type error instead of a silent bug. Readonly properties make value objects that cannot change after construction. Intersection types require an object to implement several interfaces at once. A plugin can use them as soon as its minimum PHP version is 8.1.

Problem: A plugin passes notification types around as strings ('email', 'sms'), typos reach production, and objects that carry data between the parts of the plugin are changed by accident on the way.

Solution: Turn the string constants into a backed enum with tryFrom() for input from the database or forms, write data objects with readonly promoted properties, use intersection types where a parameter must satisfy two interfaces, and declare Requires PHP: 8.1 in the plugin header.

A backed enum

<?php
enum HA_Channel: string {
    case Email = 'email';
    case Sms   = 'sms';
    case Slack = 'slack';

    public function label(): string {
        return match ( $this ) {
            self::Email => __( 'Email', 'textdomain' ),
            self::Sms   => __( 'Text message', 'textdomain' ),
            self::Slack => 'Slack',
        };
    }
}

$saved   = get_option( 'ha_channel', 'email' );
$channel = HA_Channel::tryFrom( $saved ) ?? HA_Channel::Email;

foreach ( HA_Channel::cases() as $case ) {
    printf( '<option value="%s"%s>%s</option>', esc_attr( $case->value ), selected( $case->value, $channel->value, false ), esc_html( $case->label() ) );
}

WordPress stores options and meta as strings, so values go into the database as $case->value and come back through tryFrom(), which returns null for unknown values instead of throwing like from(). match without a default fails loudly if a new case is added and the labels are not.

Readonly value objects

<?php
final class HA_Notification {
    public function __construct(
        public readonly int $user_id,
        public readonly HA_Channel $channel,
        public readonly string $message,
    ) {}
}

$note = new HA_Notification( get_current_user_id(), HA_Channel::Email, __( 'Your export is ready.', 'textdomain' ) );
// $note->message = 'x';   // Error: Cannot modify readonly property

A readonly property can be set once, in the class itself; after that any write is an error. Together with constructor promotion (PHP 8.0) a data object is a few lines. To “change” one, create a new object.

Intersection types

<?php
interface HA_Sender { public function send( HA_Notification $n ): bool; }
interface HA_Loggable { public function log_id(): string; }

function ha_dispatch( HA_Sender&HA_Loggable $sender, HA_Notification $note ): void {
    if ( ! $sender->send( $note ) ) {
        error_log( 'Notification failed via ' . $sender->log_id() );
    }
}

HA_Sender&HA_Loggable accepts only objects that implement both interfaces. Union types (A|B, PHP 8.0) mean “either”; intersection types mean “both”.

Declare the requirement

/**
 * Plugin Name: HA Notifications
 * Requires PHP: 8.1
 */

WordPress refuses to activate a plugin whose Requires PHP is higher than the server’s PHP version and shows a message instead of a fatal error. The check runs only at activation: if the server is later switched to an older PHP, a file with an enum stops with a parse error. Keep the main plugin file free of 8.1 syntax and load the other files only after version_compare( PHP_VERSION, '8.1', '>=' ). The PHP 8.0 features: match, named arguments and the nullsafe operator.

NOTE: Use these features in your own classes, not in data that WordPress serializes: an enum object stored with update_option() is serialized as an enum and cannot be read if the class is not loaded, for example after the plugin is deactivated. Store the scalar value and convert at the edge.