Home  >  Article  >  php教程  >  PHP单例模式实例浅析

PHP单例模式实例浅析

WBOY
WBOYOriginal
2016-05-26 08:20:001294browse

全局变量是面向对象程序员遇到的引发bug的主要原因之一,这是因为全局变量将类捆绑于特定的环境,破坏了封装,如果新的应用程序无法保证一开始就定义了相同的环境变量,那么一个依赖于全局变量的类就无法从一个应用程序中提取出来并应用到新的应用程序中.

什么是单例模式呢

单例模式顾名思义,就是只有一个实例,作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类我们称之为单例类。

单例模式的要点有三个:

它们必须拥有一个构造函数,并且必须被标记为private,它们拥有一个保存类的实例的静态成员变量,它们拥有一个访问这个实例的公共的静态方法,和普通类不同的是,单例类不能在其他类中直接实例化,单例类只能被其自身实例化,要获得这样的一种结果,__construct()方法必须被标记为private,如果试图用private构造函数构造一个类,就会得到一个可访问性级别的错误.

要让单例类起作用,就必须使其为其他类提供一个实例,用它调用各种方法,单例类不会创建实例副本,而是会向单例类内部存储的实例返回一个引用,结果是单例类不会重复占用内存和系统资源,从而让应用程序的其它部分更好地使用这些资源,作为这一模式的一部分,必须创建一个空的私有__clone()方法,以防止对象被复制或克隆.

返回实例引用的这个方法通常被命名为getInstance(),这个方法必须是静态的,而且如果它还没有实例化,就必须进行实例化,getInstance() 方法通过使用 instanceof 操作符和self 关键字,可以检测到类是否已经被实例化,代码如下:

header("Content-type:text/html;charset=utf-8"); 
	//单例测试类 
	class Test { 
	    private $unique; 
	    static private $instance;//静态属性保存该类实例 
	       
	    private function __construct(){//构造方法私有(防止外界调用) 
	        $this->unique=rand(0,20000); 
	    } 
	    static public function getInstance(){//静态方法提供对外接口(获取实例) 
	        if(!self::$instance instanceof self){ 
	            self::$instance=new self(); 
	        } 
	        return self::$instance; 
	    } 
	    private function __clone(){}//私有克隆方法,防止外界直接克隆该实例 
	      
	} 
	$test=Test::getInstance(); 
	$test2=Test::getInstance(); 
	  
	print_r($test);  
	print_r($test2); 
	      
	if($test===$test2){ 
	    echo '相等!'; 
	}else{ 
	    echo '不相等!'; 
	}

好了,该说书代码了,我们在程序中查询数据的操作会非常非常的多,我们不可能每次都new一个对象,这样太耗费开销了,那么我们怎么办呢,单例模式是个不错的选择,单例模式,只能实例化一次,下面看一下代码.

db.class.php,代码如下:

<?php
//数据库类、单例模式
class db {
    public $conn;
    private static $sql;
    private static $instact = null;
    private function __construct() {
        require_once (&#39;db.config.php&#39;);
        $this->conn = mysql_connect($db[&#39;host&#39;], $db[&#39;user&#39;], $db[&#39;psd&#39;]);
        if (!mysql_select_db($db[&#39;databases&#39;], $this->conn)) {
            echo "数据库连接错误";
        }
        mysql_query(&#39;set names utf8&#39;, $this->conn);
    }
    public static function getInstance() {
        if (is_null(self::$instact)) {
            self::$instact = new db;
        }
        return self::$instact;
    }
    /** 
     *数据查询
     */
    public function select($table, $condition = array() , $field = array()) {
        $where = "";
        if (!emptyempty($condition)) {
            foreach ($condition as $k => $v) {
                $where.= $k . "=&#39;" . $v . "&#39; and ";
            }
            $where = "where " . $where . " 1=1";
        }
        if (!emptyempty($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);
        $i = 0;
        while ($row = mysql_fetch_assoc($result)) {
            foreach ($row as $k => $v) {
                $resultrow[$i][$k] = $v;
            }
            $i++;
        }
        var_dump($resultrow);
    }
    /** 
     *数据添加
     */
    public function insert($table, $data) {
        $values = "";
        $datas = "";
        foreach ($data as $k => $v) {
            $values.= $k . ",";
            $datas.= "&#39;$v&#39;" . ",";
        }
        $values = rtrim($values, &#39;,&#39;);
        $datas = rtrim($datas, &#39;,&#39;);
        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 (!emptyempty($condition)) {
            foreach ($condition as $k => $v) {
                $where.= $k . "=" . $v . " and ";
            }
            $where = "where " . $where . "1=1";
        }
        $updatastr = "";
        if (!emptyempty($data)) {
            foreach ($data as $k => $v) {
                $updatastr.= $k . "=&#39;" . $v . "&#39;,";
            }
            $updatastr = "set " . rtrim($updatastr, ",");
        }
        self::$sql = "update {$table} {$updatastr} {$where}";
        return mysql_query(self::$sql);
    }
    /** 
     *数据 删除
     */
    public function delete($table, $condition) {
        $where = "";
        if (!emptyempty($condition)) {
            foreach ($condition as $k => $v) {
                $where.= $k . "=&#39;" . $v . "&#39; and ";
            }
            $where = "where " . $where . &#39;1=1&#39;;
        }
        self::$sql = "delete from {$table}  {$where}";
        return mysql_query(self::$sql);
    }
    //打印sql
    public function getlastsql() {
        echo self::$sql;
    }
}
$ne = db::getInstance();
//$ne->update(&#39;message&#39;,array(&#39;user&#39;=>&#39;wanghao&#39;,&#39;title&#39;=>&#39;sd&#39;),array(&#39;id&#39;=>&#39;5&#39;));
//echo $db->insert(&#39;message&#39;,array(&#39;user&#39;=>&#39;张三&#39;,&#39;title&#39;=>&#39;demo&#39;));
$ne->select(&#39;message&#39;, array(
    &#39;user&#39; => &#39;songlin&#39;
));
$ne->getlastsql();

数据库的配置文件,db.config.php:

<?php 
	$host = "localhost";  //主机地址 
	$user = "root";         //用户名 
	$psd= "";                 //密码 
	$databases = "ceshi"; 
	$db = array( "host" =>$host, 
	"user" =>$user, 
	"psd" =>$psd, 
	"databases"=>$databases 
	); 	


本文地址:

转载随意,但请附上文章地址:-)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn