复习下单例设计模式(实现数据库连接,以免多次实例化)

<?php
 2 class DBHelper
 3 {
 4     private $link;
 5     static private $_instance;
 6 
 7     // 连接数据库
 8     private function __construct($host, $username, $password)
 9     {
10         $this->link = mysql_connect($host, $username, $password);
11         $this->query("SET NAMES 'utf8'", $this->link);
12         //echo mysql_errno($this->link) . ": " . mysql_error($link). "n";
13         //var_dump($this->link);
14         return $this->link;
15     }
16     private function __clone()
17     {
18     }
19     public static function get_class_nmdb($host, $username, $password)
20     {
21         //$connector = new nmdb($host, $username, $password);
22         //return $connector;
23 
24         if (FALSE == (self::$_instance instanceof self)) {
25             self::$_instance = new self($host, $username, $password);
26         }
27         return self::$_instance;
28     }
29     // 连接数据表
30     public function select_db($database)
31     {
32         $this->result = mysql_select_db($database);
33         return $this->result;
34     }
35     // 执行SQL语句
36     public function query($query)
37     {
38         return $this->result = mysql_query($query, $this->link);
39     }
40     // 将结果集保存为数组
41     public function fetch_array($fetch_array)
42     {
43         return $this->result = mysql_fetch_array($fetch_array, MYSQL_ASSOC);
44     }
45     // 获得记录数目
46     public function num_rows($query)
47     {
48         return $this->result = mysql_num_rows($query);
49     }
50     // 关闭数据库连接
51     public function close()
52     {
53         return $this->result = mysql_close($this->link);
54     }
55 }
56 $connector = DBHelper::get_class_nmdb($host, $username, $password);
57 $connector -> select_db($database);
58 ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值