2017-02-14 71 views
0

我有一個PHP單例模式的問題,特別是關於實現一個mysqli包裝。PHP單例模式爲mysqli包裝

class DbHandler 
{ 

    private $mysqli; 
    private $query; 
    private $results = array(); 
    private $numRows = 0; 

    public static $instance; 

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

    public function __construct() { 
     $this->mysqli = new mysqli("127.0.0.1", "root", "", "improved_portal"); 
     if ($this->mysqli->connect_error) { 
      die($this->mysqli->connect_error); 
     } 
    } 

    public function query($statement) { 
     if ($this->query = $this->mysqli->query($statement)) { 
      foreach ($this->query as $value) { 
       $this->results[] = $value; 
      } 
      $this->numRows = $this->query->num_rows; 
      return $this; 
     } 
    } 

    public function getResults() { 
     return $this->results; 
    } 

    public function getNumRows() { 
     return $this->numRows; 
    } 

} 

當我去利用其他對象中的類時,我似乎對結果有問題。而不是每次創建一個新的對象具有唯一的$結果,似乎我正在創建初始對象的副本。例如...

$object1 = DbHandler::getInstance(); 
$object1->query("SELECT * FROM table_a")->getResults(); 

$object2 = DbHandler::getInstance(); 
$object2->query("SELECT * FROM table_b")->getResults(); 

$ object2包含兩個查詢的結果,這顯然不是我所期望的。查詢函數清楚地循環遍歷第二個查詢的結果,並將它們附加到第一個對象的$ results屬性中。我應該如何調用DbHandler類的新實例,以便每個對象都包含唯一屬性?

+0

你應該讓你的'__construct()'方法和'$ instance'財產私有的,只能使用你的類的靜態'的getInstance()'方法來創建一個對象。 –

+0

'$ this-> results'每次都必須__cleared__ –

回答

0

首先 - 這不是單身模式。當你的__construct是公開的,我可以做到這一點:

$conn1 = new DbHandler(); 
$conn2 = new DbHandler(); 
$conn3 = new DbHandler(); 

爲了防止這一點 - __construct必須受到保護/私有。

第二 - 每次您從同一個對象調用query()時,此函數會將結果添加到results屬性中。而這results屬性用於所有查詢而不清除。當然,它會保持以前的所有值。功能應該被改寫,如:

public function query($statement) { 
    // clear result from previous function call 
    $this->results = array(); 

    if ($this->query = $this->mysqli->query($statement)) { 
     foreach ($this->query as $value) { 
      $this->results[] = $value; 
     } 
     $this->numRows = $this->query->num_rows; 
     return $this; 
    } 
}