单例模式:只实例化一次,内部实例化,对外只有一个开放方法,只能通过调取该方法进行调取实例化对象。数据库连接
单例为了满足上诉内容,要满足以下条件
- 利用private构造函数使单例类不能被其他类所实例化
- 设置static变量$instance,以达到长久保存实例的效果(PHP和JAVA不同,通常情况下static变量的生命周期只有一个请求周期)
- 设置公有的静态方法getInstance()以便获取实例
单例模式又分为懒汉模式和饿汉模式,懒汉模式中,实例化的过程在getInstance中,只有调用这个方法的时候才会进行实例化;饿汉模式中,实例化的过程在初始化static变量$instance的时候,即类加载的时候,就会实例化
懒汉模式
<?php
class Single{
public $host = "localhost";
public $user = "root";
public $password = "root";
public $dbname ="login";
private $con;
// 主要区分点
private static $instance;
private function __construct(){
$this->con = mysql_connect($this->host,$this->user,$this->password);
$db = mysql_select_db($this->dbname,$this->con);
return $this->con;
}
public static function getInstance(){
// 主要区分点
if(!self::$instance instanceof self){
self::$instance = new self();
return self::$instance;
}else{
return self::$instance;
}
}
private function __clone(){
echo '此对象不允许克隆';
}
public function query($sql){
$res = mysql_query($sql,$this->con);
return $res;
}
}
$object = Single::getInstance();
$res = $object->query("insert into login (user,password)values('xiaoming','123456')");
if($res === false){
echo 'sql失败!';
}else{
echo 'sql成功!';
}
?>
饿汉模式
<?php
class Single{
public $host = "localhost";
public $user = "root";
public $password = "root";
public $dbname ="login";
private $con;
// 主要区分点
private static $instance = new self();
private function __construct(){
$this->con = mysql_connect($this->host,$this->user,$this->password);
$db = mysql_select_db($this->dbname,$this->con);
return $this->con;
}
public static function getInstance(){
// 主要区分点
return self::$instance;
}
private function __clone(){
echo '此对象不允许克隆';
}
public function query($sql){
$res = mysql_query($sql,$this->con);
return $res;
}
}
$object = Single::getInstance();
$res = $object->query("insert into login (user,password)values('xiaoming','123456')");
if($res === false){
echo 'sql失败!';
}else{
echo 'sql成功!';
}
?>