<?php
/**
* 单例模式
* 通过提供对自身共享实例的访问,单例模式用于限定特定对象只能被创建一次的情况。
*
* 应当阻止创建某个对象的多个实例时,我们最好用单例模式来创建这个对象。
*/
class Single{
protected static $_instance = NULL;
protected $_handle = NULL;
//方法前加final,则方法不能被重写;类前加final,则类不能被继承。
final protected function __construct(){
//连接数据库
$dbName = 'design';
$this->handle = mysql_connect('localhost','root','');
mysql_select_db($dbName, $this->handle);
echo $dbName.'数据库连接成功<br>';
}
//禁止克隆对象
final protected function __clone() {
}
public static function getInstance() {
if(!self::$_instance instanceof self){
self::$_instance = new self;
}
return self::$_instance;
}
}
$a = Single::getInstance();
$b = Single::getInstance();
if($a === $b){
echo '是同一对象';
}else{
echo '不是同一对象';
}