1: | <?php |
2: | |
3: | namespace ngatngay\designpattern; |
4: | |
5: | use Exception; |
6: | |
7: | class singleton |
8: | { |
9: | private static ?singleton $instance = null; |
10: | |
11: | /** |
12: | * gets the instance via lazy initialization (created on first usage) |
13: | */ |
14: | public static function get_instance(): singleton |
15: | { |
16: | if (self::$instance === null) { |
17: | self::$instance = new self(); |
18: | } |
19: | |
20: | return self::$instance; |
21: | } |
22: | |
23: | /** |
24: | * is not allowed to call from outside to prevent from creating multiple instances, |
25: | * to use the singleton, you have to obtain the instance from Singleton::getInstance() instead |
26: | */ |
27: | private function __construct() |
28: | { |
29: | } |
30: | |
31: | /** |
32: | * prevent the instance from being cloned (which would create a second instance of it) |
33: | */ |
34: | private function __clone() |
35: | { |
36: | } |
37: | |
38: | /** |
39: | * prevent from being unserialized (which would create a second instance of it) |
40: | */ |
41: | public function __wakeup() |
42: | { |
43: | throw new Exception("Cannot unserialize singleton"); |
44: | } |
45: | } |