mysqli 래퍼 구현과 관련하여 PHP 싱글 톤 패턴에 문제가 있습니다. 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에는 두 검색어의 결과가 포함되어 있습니다. 이는 분명히 내가 기대하는 바가 아닙니다. 쿼리 함수는 두 번째 쿼리의 결과를 명확하게 반복하고이를 첫 번째 개체의 $ results 속성에 추가합니다. 각 개체에 고유 한 속성이 포함되도록 DbHandler 클래스의 새 인스턴스를 어떻게 호출해야합니까?
: 기능과 같이 다시 작성해야합니다. –
'$ this-> results'는 매회 __cleared__해야합니다. –