abstrak://在這個(gè)作業(yè)中,完成數(shù)據(jù)庫(kù)連接的單例模式,和課堂中例子的唯一區(qū)別,就是需要在類的構(gòu)造函數(shù)中完成數(shù)據(jù)庫(kù)的連接操作,這里使用mysqli功能完成和數(shù)據(jù)庫(kù)的連接,具體代碼如下<?phpheader("content-type:text/html;charset=utf-8");//開啟支持中文class DbSingleton{ private $c
//在這個(gè)作業(yè)中,完成數(shù)據(jù)庫(kù)連接的單例模式,和課堂中例子的唯一區(qū)別,就是需要在類的構(gòu)造函數(shù)中完成數(shù)據(jù)庫(kù)的連接操作,這里使用mysqli功能完成和數(shù)據(jù)庫(kù)的連接,具體代碼如下
<?php
header("content-type:text/html;charset=utf-8");//開啟支持中文
class DbSingleton
{
private $charset = "utf8"; //字符串編碼
//創(chuàng)建類的內(nèi)部靜態(tài)屬性,保存類的唯一實(shí)例
private static $instance = NULL;
//關(guān)閉外部接口
private function __construct($host, $username, $password, $dbname, $port)
{
//mysqli方法連接數(shù)據(jù)庫(kù)
$link = mysqli_connect($host, $username, $password, $dbname, $port);
if (!$link) {
die("連接錯(cuò)誤: " . mysqli_connect_error());
}
// 修改數(shù)據(jù)庫(kù)連接字符集為 utf8
mysqli_set_charset($link, $this->charset);
return $link;
}
//關(guān)閉clone接口
private function __clone()
{
}
//創(chuàng)建一個(gè)外部接口,創(chuàng)建并返回唯一實(shí)例
public static function getInstance($host, $username, $password, $dbname, $port)
{
if (is_null( static::$instance) ) ) {
static::$instance = new static($host, $username, $password, $dbname, $port);
}
return static::$instance;
}
}
//從外部實(shí)例化
$host = '127.0.0.1';
$username = 'root';
$password = '123456';
$dbname = 'test';
$port = 3306;
$Db = DbSlingleton :: getInstance
($host, $username, $password, $dbname, $port);
var_dump($db);
Guru membetulkan:天蓬老師Masa pembetulan:2019-04-10 13:26:43
Rumusan guru:?jiǎn)卫J? 類似之前的獨(dú)生子女, 一家就一個(gè)孩子, 你可以想像成類, 這個(gè)類僅允許生一個(gè)孩子