Make WordPress Core


Ignore:
Timestamp:
09/02/2026 08:47:56 PM (6 weeks ago)
Author:
SergeyBiryukov
Message:

Code Modernization: Use the null coalescing assignment operator in singleton accessors.

Replaces the null-guard singleton pattern in get_instance() accessors with the null coalescing assignment operator (??=):

// Before
public static function get_instance() {
	if ( null === self::$instance ) {
		self::$instance = new self();
	}

	return self::$instance;
}


// After
public static function get_instance() {
	self::$instance ??= new self();

	return self::$instance;
}

Both forms are functionally identical; ??= is shorter and states the intent directly.

Why this is safe

  • ??= requires PHP 7.4, which is already the minimum supported version.
  • The operator short-circuits: the right-hand side is only evaluated when the left-hand side is null or not set, so the object is still instantiated exactly once.
  • The operator is already used elsewhere in core, e.g. in wp-includes/l10n.php and wp-includes/view-config.php, so this only makes existing usage consistent.
  • No behavior change.

Intentionally not changed

WP_Abilities_Registry::get_instance() and WP_Ability_Categories_Registry::get_instance() use the same guard, but their blocks contain additional side effects beyond the assignment:

if ( null === self::$instance ) {
	self::$instance = new self();

	WP_Ability_Categories_Registry::get_instance();
	do_action( 'wp_abilities_api_init', self::$instance );
}

Converting these to ??= would cause the action and the nested registry initialization to run on every call instead of only on the first, so both are left as-is.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/12889.

Props Soean, mukesh27.
See #65823.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-admin/includes/class-wp-site-health.php

    r63342 r63443  
    7878         */
    7979        public static function get_instance() {
    80                 if ( null === self::$instance ) {
    81                         self::$instance = new WP_Site_Health();
    82                 }
     80                self::$instance ??= new WP_Site_Health();
    8381
    8482                return self::$instance;
Note: See TracChangeset for help on using the changeset viewer.