PHPシングルトンパターンに問題があります。具体的には、mysqliラッパーの実装に関してです。私は他のオブジェクトにクラスを利用するために行くときmysqliラッパーのPHPシングルトンパターン
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は、明らかに私が期待していないものです。クエリ関数は、2番目のクエリの結果を明確にループし、最初のオブジェクトの$ resultsプロパティに追加します。各オブジェクトに固有のプロパティが含まれるように、DbHandlerクラスの新しいインスタンスをどのように呼び出す必要がありますか?
:機能は次のように書き直す必要があります。 –
毎回 '$ this-> results'を__cleared__する必要があります –