<?php
/**
 * Singleton trait.
 *
 * @since   1.0.0
 * @package DonationRouter
 */

declare( strict_types=1 );
namespace DonationRouter;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Provides a thread-safe singleton accessor for any class that uses it.
 *
 * @since 1.0.0
 */
trait Singleton {

	/**
	 * Sole instance.
	 *
	 * @since 1.0.0
	 *
	 * @var static|null
	 */
	protected static ?self $instance = null;

	/**
	 * Return the singleton instance, creating it on first call.
	 *
	 * @since 1.0.0
	 *
	 * @return static
	 */
	public static function instance(): static {
		if ( null === static::$instance ) {
			// @phpstan-ignore-next-line new.static
			static::$instance = new static();
		}

		return static::$instance;
	}

	/**
	 * Prevent cloning.
	 *
	 * @since 1.0.0
	 */
	private function __clone() {}
}
