-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.php
65 lines (52 loc) · 1.25 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
/**
* Created by PhpStorm.
* User: netAir
* Date: 17-7-21
* Time: 下午4:14
*/
class InventoryConnection
{
protected static $instance;
protected $dbh;
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
protected function __construct()
{
$this->dbh = new PDO('mysql:host=localhost;dbname=test', 'test', '123456');
var_dump('执行链接数据库操作');
}
public function updateQuantity(string $band, string $title, string $number)
{
//......
}
}
class CD
{
protected $title;
protected $band;
public function __construct(string $title, string $band)
{
$this->title = $title;
$this->band = $band;
}
public function buy()
{
$inventory = InventoryConnection::getInstance();
$inventory->updateQuantity($this->band, $this->title, -1);
}
}
$boughtCDs = [
['band' => 'band1', 'title' => 'title1'],
['band' => 'band2', 'title' => 'title2']
];
foreach ($boughtCDs as $boughtCD) {
$cd = new CD($boughtCD['title'], $boughtCD['band']);
$cd->buy();
}
//两次购买操作只会执行一次数据库的连接