配置文件读取类conf.class.php 单例模式应用

在php项目开发中,数据库配置文件读写类是必须的,以前写小程序时自己也感到实例化几个数据库连接对象不好,奈何水平有限,就是没想到单例模式,知道不会用啊。

特殊性:大家都来读取这个配置文件读取类,需要保持统一性,必须做成单例模式,保证实例化出的对象的唯一性。

<?php
//配置文件读写类 单例模式
class conf{
	//声明一个静态属性来存放实例
	protected static $ins=null;
	protected $data=array();	//声明一个数组 用于存放读取来的数据库类信息
	
	//首先将类的构造函数和克隆方法写死
	final protected function __construct(){
		//一次性将配置文件信息读取过来并赋给data属性,这样以后就不用管配置文件了
		//需要配置文件值事,直接从data属性中找即可	
		include('../include/config.inc.php');
		$this->data=$_CFG;		//将配置数组赋给成员变量
	}
	
	final protected function __clone(){
		
	}
	
	//写一个静态方法来声明并判断实例,存在则返回已存在的实例,不存在则实例化新的,保证实例对象的唯一性
	public static function getIns(){
		if(self::$ins instanceof self){
			return self::$ins;
		}else{
			self::$ins=new self();
			return self::$ins;	
		}
	}
	
	//使用魔术方法读取data中的信息
	public function __get($key){
		if(array_key_exists($key,$this->data)){
			return $this->data[$key];
		}else{
			return null;	
		}
	}
	
	//使用魔术方法 在运行期动态增加或改变配置选项
	public function __set($key,$value){
		$this->data[$key]=$value;
	}
	
	
}

$conf=conf::getIns();
var_dump($conf);

//读取选项
echo $conf->host;
echo '<br>';
var_dump($conf->author);
echo $conf->user.'<br>';

//动态增加选项
$conf->website='www.seoalphas.com';
echo $conf->author;
?>

运行结果如下:
object(conf)[1]
  protected 'data' => 
    array (size=3)
      'host' => string 'localhost' (length=9)
      'user' => string 'root' (length=4)
      'pwd' => string '123456' (length=6)
localhost
null
root
www.seoalphas.com

猜你喜欢

转载自blog.csdn.net/cangxie8/article/details/50264667