php单例模式

 

单例模式确保一个类只能有1个实例(new 一次),并且在类内部自动实例化,并向系统全局提供这个实例;
1:要有一个私有的静态变量(以mysql类为例),用来保存这个唯一的实例
1 class mysql extends db {
2     private static $insance = NULL;
}

 2:因为要自动实例化,所以要有__construct()构造函数,在调用的时候用来初始化,又因为要确保唯一,构造函数和克隆函数必须声明为私有,防止外部程序new类从而失去单例模式的意义:

class mysql extends db {
    private static $instance = null;
    private function __construct(){
    
    }
    private function __clone(){

    }
}

 

  

3:虽然只有一个实例,但是必须可以访问,所以需要一个公共的静态方法,;


class mysql extends db {
    private static $instance = null;
    private function __construct(){
    
    }
    private function __clone(){

    }
  
public static function getInstance (){
    

       if(!(self::$ins instanceof self)) {

                 self::$instance = new self();
              }

                 return self::$instance;//返回唯一实例的一个引用,self是类的指针,this是对象的指针,parent是父类的指针;

   }
}

 

4:mysql的单例模式

<?php
class db {
    private static $conn;   //存放连接语句
    private static $sql; //存放查询语句
    private static $instance=null; //存放实例
    private function __construct(){
        require_once('db.config.php');
        $this->conn = mysql_connect($db['host'],$db['user'],$db['password']);
        if(!mysql_select_db($db['database'],$this->conn)){
            echo "失败";
        };
        mysql_query('set names utf8',$this->conn);        
    }
    public static function getInstance(){
        if(is_null(self::$instance)){
            self::$instance = new db;
        }
        return self::$instance;
    }
    /**
     * 查询数据库
     */
    public function select($table,$condition=array(),$field = array()){
        $where='';
        if(!empty($condition)){
            
            foreach($condition as $k=>$v){
                $where.=$k."='".$v."' and ";
            }
            $where='where '.$where .'1=1';
        }
        $fieldstr = '';
        if(!empty($field)){
            
            foreach($field as $k=>$v){
                $fieldstr.= $v.',';
            }
             $fieldstr = rtrim($fieldstr,',');
        }else{
            $fieldstr = '*';
        }
        self::$sql = "select {$fieldstr} from {$table} {$where}";
        $result=mysql_query(self::$sql,$this->conn);
        $resuleRow = array();
        $i = 0;
        while($row=mysql_fetch_assoc($result)){
            foreach($row as $k=>$v){
                $resuleRow[$i][$k] = $v;
            }
            $i++;
        }
        return $resuleRow;
    }
    /**
     * 添加一条记录
     */
     public function insert($table,$data){
         $values = '';
         $datas = '';
         foreach($data as $k=>$v){
             $values.=$k.',';
             $datas.="'$v'".',';
         }
         $values = rtrim($values,',');
         $datas   = rtrim($datas,',');
         self::$sql = "INSERT INTO  {$table} ({$values}) VALUES ({$datas})";
        if(mysql_query(self::$sql)){
            return mysql_insert_id();
        }else{
            return false;
        };
     }
     /**
      * 修改一条记录
      */
    public function update($table,$data,$condition=array()){
        $where='';
        if(!empty($condition)){
            
            foreach($condition as $k=>$v){
                $where.=$k."='".$v."' and ";
            }
            $where='where '.$where .'1=1';
        }
        $updatastr = '';
        if(!empty($data)){
            foreach($data as $k=>$v){
                $updatastr.= $k."='".$v."',";
            }
            $updatastr = 'set '.rtrim($updatastr,',');
        }
        self::$sql = "update {$table} {$updatastr} {$where}";
        return mysql_query(self::$sql);
    }
    /**
     * 删除记录
     */
     public function delete($table,$condition){
         $where='';
        if(!empty($condition)){
            
            foreach($condition as $k=>$v){
                $where.=$k."='".$v."' and ";
            }
            $where='where '.$where .'1=1';
        }
        self::$sql = "delete from {$table} {$where}";
        return mysql_query(self::$sql);
        
     }
    
    public static function getLastSql(){
        echo self::$sql;
    }
    
    
    
}

$db = db::getInstance();
//$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password'));
//echo $db->insert('demo',array('name'=>'最近你啦','password'=>'123'));
//echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1));
echo $db->delete('demo',array('id'=>'2'));
db::getLastSql();
echo "<pre>";
?>

 

posted @ 2014-10-16 16:10  王孙将归  阅读(132)  评论(0编辑  收藏  举报