class-singleton.php
62 lines
| 1 | <?php |
| 2 | /** |
| 3 | * The singleton class file. |
| 4 | * |
| 5 | * @package GenerateBlocks\Utils |
| 6 | */ |
| 7 | |
| 8 | if ( ! defined( 'ABSPATH' ) ) { |
| 9 | exit; // Exit if accessed directly. |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * The GenerateBlocks Singleton class. |
| 14 | * |
| 15 | * @since 1.9.0 |
| 16 | */ |
| 17 | class GenerateBlocks_Singleton { |
| 18 | |
| 19 | /** |
| 20 | * Child class instances. |
| 21 | * |
| 22 | * @var array<static> |
| 23 | */ |
| 24 | private static $instances = []; |
| 25 | |
| 26 | /** |
| 27 | * The singleton constructor can not be public. |
| 28 | */ |
| 29 | final protected function __construct() { |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Not allowed to clone a singleton. |
| 34 | */ |
| 35 | protected function __clone() { |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Not allowed to un-serialize a singleton. |
| 40 | * |
| 41 | * @throws Exception Cannot un-serialize a singleton. |
| 42 | */ |
| 43 | public function __wakeup() { |
| 44 | throw new Exception( 'Cannot un-serialize singleton' ); |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Get the class instance. |
| 49 | * |
| 50 | * @return static |
| 51 | */ |
| 52 | public static function get_instance(): GenerateBlocks_Singleton { |
| 53 | $subclass = static::class; |
| 54 | |
| 55 | if ( ! isset( self::$instances[ $subclass ] ) ) { |
| 56 | self::$instances[ $subclass ] = new static(); |
| 57 | } |
| 58 | |
| 59 | return self::$instances[ $subclass ]; |
| 60 | } |
| 61 | } |
| 62 |