-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSingleton.php
65 lines (53 loc) · 1.33 KB
/
Singleton.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace DesignPatterns\Creational;
/**
* Lets you ensure that a class has only one instance and providing a global access to this instance
*/
trait Singleton
{
protected static $instance;
final public static function getInstance()
{
return isset(static::$instance)
? static::$instance
: static::$instance = new static;
}
/**
* Singleton's constructor should not be public. However, it can't be
* private either if we want to allow subclassing.
*/
protected function __construct()
{
$this->init();
}
/**
* Some initialization can be here
*/
protected function init()
{
}
// Cloning and unserialization are not permitted for singletons
final private function __clone()
{
}
final private function __wakeup()
{
}
}
class Application
{
use Singleton;
protected function init()
{
echo 'Application is initialized once ...';
}
}
// there is the only one way to get an application instance
$app = Application::getInstance();
// every call will give the same instance
assert(Application::getInstance() === $app);
/* Output: Application is initialized once ... */
/* Next calls will produce errors:
$app = new Application();
$app = clone $app;
$app = unserialize(serialize($app)); */