Total Complexity | 5 |
Total Lines | 47 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
7 | abstract class Singleton |
||
8 | { |
||
9 | /** |
||
10 | * Hold the classes on instance. |
||
11 | * |
||
12 | * @var array |
||
13 | */ |
||
14 | private static array $instances = []; |
||
15 | |||
16 | public function __construct(string $index = 'main') |
||
17 | { |
||
18 | $className = self::getClassName(); |
||
19 | if (isset(self::$instances[$className][$index])) { |
||
20 | die("Please use '$className:getInstance()' instead of 'new' to instantiate a Singleton."); |
||
|
|||
21 | } |
||
22 | self::$instances[$className][$index] = $this; |
||
23 | } |
||
24 | |||
25 | /** |
||
26 | * Returns the class name. |
||
27 | * |
||
28 | * @return string |
||
29 | */ |
||
30 | protected static function getClassName(): string |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * The object is created from within the class itself only if the class |
||
38 | * has no instance. |
||
39 | * |
||
40 | * We opted to use an array to make several singletons according to the |
||
41 | * index passed to getInstance |
||
42 | * |
||
43 | * @param string $index |
||
44 | * |
||
45 | * @return mixed |
||
46 | */ |
||
47 | public static function getInstance(string $index = 'main') |
||
54 | } |
||
55 | |||
56 | } |
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.