单列模式保证系统中一个类只有一个实例。即一个类只有一个对象实例。
特点:
1.一个类只能有一个对象;
2.必须是自行创建这个类的对象;
3.要想整个系统提供这一个对象;
<?php
class single{
private static $instance;
public function __construct(){
echo "自己初始化<br/>";
}
//防止克隆对象
public function __clone(){}
/** 实例化self */
public static function getInstance(){
if(!self::$instance instanceof self){
self::$instance = new self();
}
return self::$instance;
}
/* 方法 */
public function getName(){
return "name";
}
}
$obj = single::getInstance();
echo $obj->getName();
?>
单列模式简单应用:
class mysqlConnect{
private static $instance;
private $db;
public function __construct($config){
try{
$this->db = new \PDO($config['host'], $config['user'], $config['password']);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->exec('set names utf8');
}catch(PDOException $e){
var_dump($e->getMessage());
}
}
public static function getInstance($config){
if(!self::$instance instanceof self){
self::$instance = new self($config);
}
return self::$instance;
}
public function query(){
$stmt = $this->db->query('select 1+1 as sum');
//var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));
//$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$res = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($res['sum']);
}
}
$config = [
'host' => 'mysql:host=localhost;dbname=demo',
'user' => 'root',
'password' => '123456'
];
$obj = mysqlConnect::getInstance($config);
$obj->query();
网友评论