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