• php 单例模式


    单例模式
    当需要保证某个对象只能有一个实例的时候,单例模式非常有用。它把创建对象的控制权委托到一个单一的点上,任何时候应用程序都只会仅有一个实例存在。

    单例模式中必须包含:private 的构造函数、静态变量、公共静态方法、private clone方法。

    下面举个栗子

    <?php
    /*
    * mysql 单例
    */
    class mysql{
        private $host    ='yourhost'; //数据库主机
        private $user     = 'youruser'; //数据库用户名
        private $pwd     = 'yourpwd'; //数据库用户名密码
        private $database = 'database'; //数据库名
        private $charset = 'utf8'; //数据库编码,GBK,UTF8,gb2312
        private $link;             //数据库连接标识;
        private $rows;             //查询获取的多行数组
        static $_instance; //存储对象
        /**
         * 私有构造函数
         */
        private function __construct($pconnect = false) {
            if (!$pconnect) {
                $this->link = @ mysql_connect($this->host, $this->user, $this->pwd) or $this->err();
            } else {
                $this->link = @ mysql_pconnect($this->host, $this->user, $this->pwd) or $this->err();
            }
            mysql_select_db($this->database) or $this->err();
            $this->query("SET NAMES '{$this->charset}'", $this->link);
            return $this->link;
        }
        /**
         * 防止被克隆
         *
         */
        private function __clone(){}
        public static function getInstance($pconnect = false){
            if(FALSE == (self::$_instance instanceof self)){
                self::$_instance = new self($pconnect);
            }
            return self::$_instance;
        }
        /**
         * 查询
         */
        public function query($sql, $link = '') {
            $this->result = mysql_query($sql, $this->link) or $this->err($sql);
            return $this->result;
        }
        /**
         * 单行记录
         */
        public function getRow($sql, $type = MYSQL_ASSOC) {
            $result = $this->query($sql);
            return @ mysql_fetch_array($result, $type);
        }
        /**
         * 多行记录
         */
        public function getRows($sql, $type = MYSQL_ASSOC) {
            $result = $this->query($sql);
            while ($row = @ mysql_fetch_array($result, $type)) {
                $this->rows[] = $row;
            }
            return $this->rows;
        }
        /**
         * 错误信息输出
         */
        protected function err($sql = null) {
            
        }
    }
    //用例
    $db = mysql::getInstance();
    $db2 = mysql::getInstance();
    $data = $db->getRows('select * from blog');
    //print_r($data);
    //判断两个对象是否相等
    if($db === $db2){
        echo 'true';
    }
    ?>
  • 相关阅读:
    /proc/kcore失效,调试其文件系统相关模块,使重新正常工作
    linux内核的preempt抢占调度,preempt_count抢占保护“锁”
    linux内核的tiny rcu, tree rcu
    futex-based pthread_cond 源代码分析
    linux 内核的futex
    phtread_mutex 组合
    linux 内核的rt_mutex 锁操作实现的临界区
    linux 内核的RCU本质
    Spring Data(一)概念和仓库的定义
    MongoDB之分片集群(Sharding)
  • 原文地址:https://www.cnblogs.com/pfdltutu/p/9019194.html
Copyright © 2020-2023  润新知