我最近遇到了分頁的需求,我將使用它很多,所以我覺得一個類將是一個完美的適合,爲某種原因,當我嘗試使用__construct
我得到的致命錯誤:調用成員函數prepare()null,如果__construct函數存在
Call to a member function prepare() on null Thrown in '\App\Helpers\PaginationHelper.php' on line 31
第31行是這樣的:
$sth = $this->db->prepare('SELECT * FROM '. $this->table_name .' ORDER BY id LIMIT :page_first_result, :per_page');
。
這是一個很大的混亂,因爲我剛剛開始,但對於我的生活我無法弄清楚這個錯誤,我已經閱讀了一些其他問題有相同的錯誤,但他們都與PDO有關連接,不像這個問題。
\核心\型號只是延伸的PDO連接
class PaginationHelper extends \Core\Model {
public $results = [];
public $tabs = '';
public $set_data;
public $table_name;
public $results_per_page;
public function __construct($sd){
$this->set_data = $sd;
}
public function table_name($tn){
$this->table_name = $tn;
}
public function results_per_page($rpp){
$this->results_per_page = $rpp;
}
public function retrieveData($page_first_result, $per_page){
$sth = $this->db->prepare('SELECT * FROM '. $this->table_name .' ORDER BY id LIMIT :page_first_result, :per_page');
$sth->bindValue(':page_first_result', $page_first_result, PDO::PARAM_INT);
$sth->bindValue(':per_page', $per_page, PDO::PARAM_INT);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
public function getResults(){
$number_of_results = $this->set_data;
$this->number_of_pages = ceil(count($number_of_results)/$this->results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['pagination'])) {
$this->page = 1;
} else {
$this->page = $_GET['pagination'];
}
$this_page_first_result = ($this->page - 1) * $this->results_per_page;
$fetch = $this->retrieveData($this_page_first_result, $this->results_per_page);
foreach($fetch as $data){
$this->results[] = $data;
}
return $this;
}
public function loopResults(){
return $this->results;
}
public function getTabs(){
if($this->page == 1){
$this->back = $this->page;
} else {
$this->back = $this->page-1;
}
if($this->page == $this->number_of_pages){
$this->next = $this->page;
} else {
$this->next = $this->page + 1;
}
$this->tabs .= '
<div class="pagination">
<a class="pagination__buttons-href" href="?pagination='.$this->back.'"><span class="pagination__buttons flaticon-keyboard-left-arrow-button"></span></a>
<span class="pagination__current_page"> '. $this->page .' </span>
<a class="pagination__buttons-href" href="?pagination='. $this->next .'"><span class="pagination__buttons flaticon-keyboard-right-arrow-button"></span></a>
</div>
';
return $this->tabs;
}
}
現在,這裏是一些有趣的事情:如果我刪除__construct function
,創造把$ set_data性質類似下面的新方法,一切完美。
public function set_data($sd){
$this->set_data = $sd;
}
這是我如何調用類:
這是我如何打電話與功能set_data類:
$pagination = new PaginationHelper();
$pagination->set_data($array_data);
$pagination->table_name('recipe');
$pagination->results_per_page(20);
$pagination->getResults();
您需要正確啓動'$ this-> db',可能是在構造函數中。現在它只是一個未初始化的(並且未聲明的)屬性 – Calimero
\ Core \ Model將數據庫類中的構造函數傳遞給'$ this-> db'。 – Craig
錯誤信息明確表示否則。必須明確調用父構造函數才能運行它。 – Calimero