Skip to content

Commit 95041d0

Browse files
committed
Singleton
1 parent 9162f5e commit 95041d0

File tree

2 files changed

+138
-0
lines changed

2 files changed

+138
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ See details on http://maxsite.org/page/php-patterns
66
* "Fluent interface" (Structural)
77
* "Factory method" / "Virtual Constructor" (Creational)
88
* "Abstract factory" (Creational)
9+
* "Singleton" (Creational)
910

1011

1112
(c) MaxSite.org, 2019, http://maxsite.org/

Singleton/index.php

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
<?php
2+
3+
/**
4+
* Design pattern "Singleton" (Creational)
5+
* This is demo code
6+
* See for details: http://maxsite.org/page/php-patterns
7+
*/
8+
9+
/**
10+
* Base
11+
*/
12+
trait SingletonTrait
13+
{
14+
private static $instance;
15+
16+
public static function getInstance()
17+
{
18+
if (empty(self::$instance)) self::$instance = new static();
19+
20+
return self::$instance;
21+
}
22+
23+
private function __construct()
24+
{
25+
}
26+
private function __clone()
27+
{
28+
}
29+
private function __wakeup()
30+
{
31+
}
32+
}
33+
34+
/**
35+
* Class for sample
36+
*/
37+
class Foo
38+
{
39+
/**
40+
* Add SingletonTrait to this class
41+
*/
42+
use SingletonTrait;
43+
44+
/**
45+
* Class's own methods...
46+
*/
47+
private $var = [];
48+
49+
public function addVal($v)
50+
{
51+
$this->var[] = $v;
52+
}
53+
54+
public function getVal()
55+
{
56+
return $this->var;
57+
}
58+
}
59+
60+
61+
/**
62+
* demo
63+
*/
64+
65+
echo '<pre>'; // for print in browser
66+
67+
# $foo = new Foo(); // Error: Call to private Foo::__construct()
68+
69+
/**
70+
* get instance in $foo1
71+
*/
72+
$foo1 = Foo::getInstance();
73+
74+
/**
75+
* add values
76+
*/
77+
$foo1->addVal('first');
78+
$foo1->addVal('second');
79+
80+
/**
81+
* control
82+
*/
83+
print_r($foo1->getVal());
84+
/*
85+
Array
86+
(
87+
[0] => first
88+
[1] => second
89+
)
90+
*/
91+
92+
/**
93+
* new variable $foo2
94+
*/
95+
$foo2 = Foo::getInstance();
96+
print_r($foo2->getVal());
97+
/*
98+
Array
99+
(
100+
[0] => first
101+
[1] => second
102+
)
103+
*/
104+
105+
/**
106+
* add value to $foo
107+
*/
108+
$foo1->addVal('new value');
109+
110+
/**
111+
* control $foo1
112+
*/
113+
print_r($foo1->getVal());
114+
/*
115+
Array
116+
(
117+
[0] => first
118+
[1] => second
119+
[2] => new value
120+
)
121+
*/
122+
123+
/**
124+
* control $foo2
125+
*/
126+
print_r($foo2->getVal());
127+
/*
128+
Array
129+
(
130+
[0] => first
131+
[1] => second
132+
[2] => new value
133+
)
134+
*/
135+
136+
137+
# end of file

0 commit comments

Comments
 (0)