简介:
只允许该类自己创建该类的唯一对象,防止直接创建对象和克隆 对外暴露一个统一的接口,通过静态方法获取该对象 该类防止被直接创建和克隆
优点:
new对象的操作过多会消耗内存,使用单例模式生成一个对象后, 该对象可以被其它众多对象所使用
使用场景:
一般用于数据库操作类
实例:
class Db
{
private static $_instance;
private static $_dbConnect;
private $_dbConfig = array(
'host' => '127.0.0.1',
'user' => 'root',
'password' => '123456',
'database' => 'wangxiao_test'
);
private function __construct()
{
}
private function __clone()
{
trigger_error("Can't clone object", E_USER_ERROR);
}
public static function getInstance()
{
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function connect()
{
self::$_dbConnect = @new mysqli($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);
if (!self::$_dbConnect) {
throw new Exception("mysql connect error" . mysqli_connect_error());
}
self::$_dbConnect->query("set names 'utf8';");
mysqli_select_db(self::$_dbConnect, $this->_dbConfig['database']);
return self::$_dbConnect;
}
}
$mysqli = Db::getInstance();
try {
$coon = $mysqli->connect();
$sql = 'select * from users limit 10';
$res = mysqli_query($coon, $sql);
while ($row = mysqli_fetch_assoc($res)) {
var_dump($row);
}
} catch (Exception $e) {
echo "sorry,error was happened." . $e->getMessage();
}
|