zoukankan      html  css  js  c++  java
  • php 类单例模式

    单例模式顾名思义,就是只有一个实例。由此借鉴之,在数据库操作中,对于同一个库只允许一个实例存在很重要.
    <?php

    class mysql
    {
        
    protected $db;
        
    static private $instance = null;
        
    /**
         * 得到数据库连接
         *
         
    */
        
    private function getDb()
        {

            
    //已有连接
            if(isset(self::$instance))
            {
                
    $this->db = self::$instance;
            }
            
    else
            {
                
    //无此连接
                global $__db__;
                
    extract($__db__);
                
    $dsn = "mysql:host=$host;port=$port;dbname=$database";

                
    try {
                    
    $this->db = new PDO($dsn, $user, $password);
                } 
    catch (PDOException $e) {
                    
    echo 'Connection failed: ' . $e->getMessage();
                }
                self
    ::$instance = $this->db;
            }
        }
        
    /**
         * 运行sql
         *
         * @param sql $sql
         
    */

        
    private function query($sql)
        {
                    
    $this->getDb();
                    
    ......
        }

    }
    ?>


  • 相关阅读:
    zipalign内存对齐优化
    反编译 waring...
    android.os.NetworkOnMainThreadException
    android:LayoutInflater
    Notification NotificationManager RemoteViews PendingIntent
    WebView WebViewClient WebChromeClient
    寒假1
    冻死可怕了
    一个人失眠
    军训快乐
  • 原文地址:https://www.cnblogs.com/liulei/p/1760508.html
Copyright © 2011-2022 走看看