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