PHP Singleton Mode

Server environment

1
2
3
4
5
$ cat /etc/issue
Ubuntu 16.04.2 LTS

$ php -v
PHP 7.0.22-0ubuntu0.16.04.1 (cli) ( NTS )

The Real One and Modern way to make Singleton Pattern is:

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
<?php

Class Singleton
{

/**
* Singleton constructor.
* Make constructor private. so nobody can call "new Class".
*/
private function __construct()
{
}

/**
* Make clone magic method private. so nobody can clone instance.
*/
private function __clone()
{
}

/**
* Make sleep magic method private. so nobody can serialize instance.
*/
private function __sleep()
{
}

/**
* Make wakeup magic method private. so nobody can unserialize instance.
*/
private function __wakeup()
{
}

/**
* Call this method to get singleton
* @return static
*/
public static function Instance()
{
static $instance = false;

if ($instance === false) {
$instance = new static();
}
return $instance;
}
}

So now you can use it like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

class Database extends Singleton
{
protected $label;

/**
* @return mixed
*/
public function getLabel()
{
return $this->label;
}

/**
* @param mixed $label
*/
public function setLabel($label)
{
$this->label = $label;
}
}

Test it

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

$database = Database::Instance();
$database->setLabel("Liang-app");

echo $database->getLabel() . PHP_EOL; //Liang-app

$other_db = Database::Instance();
echo $other_db->getLabel() . PHP_EOL; //Liang-app

$other_db->setLabel("Liang-app-2");
echo $database->getLabel() . PHP_EOL; //Liang-app-2
echo $other_db->getLabel() . PHP_EOL; //Liang-app-2

Share