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

PHP: OOP connection to database use multiple

我使用此代码连接到数据库

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;
    }
}

并使用此代码连接 select 来自数据库

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

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

在 运行 这段代码之后,打印在页面上:

CONNECTCONNECT

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

利用单例模式来提供这个

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;
     }
}

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

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

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