abstrakt:<?phpheader("content-type:text/html;charset=utf-8");class DbSingleton{ private $charset = "utf8"; //字符串編碼 //私有的成員屬性-為了防止在類外
<?php
header("content-type:text/html;charset=utf-8");
class DbSingleton
{
private $charset = "utf8"; //字符串編碼
//私有的成員屬性-為了防止在類外引入這個存放對象的屬性
private static $instance = NULL; //存儲對象
//私有的構(gòu)造方法-為了防止在類外使用new關(guān)鍵字實例化對象
private function __construct($host, $username, $password, $dbname, $port)
{
$link = mysqli_connect($host, $username, $password, $dbname, $port);
if (!$link) {
die("連接錯誤: " . mysqli_connect_error());
}
else{
echo "連接成功".'<br>';
}
// 修改數(shù)據(jù)庫連接字符集為 utf8
mysqli_set_charset($link, $this->charset);
return $link;
}
//私有的克隆方法-為了防止在類外通過clone成生另一個對象
private function __clone()
{
}
//公有的靜態(tài)方法-為了讓用戶進行實例化對象的操作
public static function getInstance($host, $username, $password, $dbname, $port)
{
if (!self::$instance instanceof self) {
self::$instance = new self($host, $username, $password, $dbname, $port);
}
return self::$instance;
}
}
//數(shù)據(jù)庫測試:
$host = '127.0.0.1';
$username = 'root';
$password = 'root';
$dbname = 'test';
$port = 3306;
$db = DbSingleton::getInstance($host, $username, $password, $dbname, $port);
var_dump($db);
Korrigierender Lehrer:查無此人Korrekturzeit:2019-05-09 14:11:30
Zusammenfassung des Lehrers:完成的不錯。編程還有很多模式。多了解,可以更好的提高能力。繼續(xù)加油