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.