PHP:与数据库的OOP连接使用多个

时间:2016-11-08 11:31:14

标签: php database oop database-connection

我使用此代码连接数据库

class DB {
    private $connect;

    public function connect(){
        if(!$this->connect){
            include "config.php";
            echo "CONNECT";
            $this->connect = mysqli_connect($config['HOST'],$config['USER'],$config['PASS']);
            if($this->connect){
                $select = mysqli_select_db($this->connect,$config['NAME']);
                if(!$select){
                    echo "Not Found Database !";
                    exit();
                }
            } else {
                echo "Not Connect To Database !";
                exit();
            }
        }
        return $this->connect;
    }

    public function query($query) {
        $result = $this->connect()->query($query);
        return $result;
    }
}

使用此代码进行连接,然后从数据库中选择

$db = new DB();
$connect = $db->connect();

$db = new DB();
$way = $db->select("SELECT * FROM `setting`");

运行此代码后,在页面上打印:

CONNECTCONNECT

为什么不在if(!$this->connect){行中3工作并连接两次?

1 个答案:

答案 0 :(得分:0)

利用单例模式提供此

class DB {
     private $connect;
     protected static $instance;

     public static function getInstance() {
          if (null === self::$instance) {
               self::$instance = new self;
          }
          return self::$instance;
     }

     protected function __clone() {}
     protected function __construct() {}

     public function connect(){
          if(!$this->connect){
               include "config.php";
               echo "CONNECT";
               $this->connect = mysqli_connect($config['HOST'],$config['USER'],$config['PASS']);
               if($this->connect){
                    $select = mysqli_select_db($this->connect,$config['NAME']);
                    if(!$select){
                         echo "Not Found Database !";
                         exit();
                    }
               } else {
                    echo "Not Connect To Database !";
                    exit();
               }
          }
          return $this->connect;
     }

     public function query($query) {
          $result = $this->connect()->query($query);
          return $result;
     }
}

然后在应用中的任何位置使用类实例

$db = DB::getInstance();
$connect = $db->connect();

$db = DB::getInstance();
$way = $db->select("SELECT * FROM `setting`");