要實(shí)現(xiàn)PHP分頁(yè)封裝和調(diào)用,可以自定義一個(gè)分頁(yè)類來(lái)處理分頁(yè)邏輯。下面是一個(gè)簡(jiǎn)單的示例代碼,展示了如何實(shí)現(xiàn)PHP分頁(yè)封裝和調(diào)用:
class Pagination {
private $totalRecords;
private $recordsPerPage;
private $currentPage;
public function __construct($totalRecords, $recordsPerPage, $currentPage) {
$this->totalRecords = $totalRecords;
$this->recordsPerPage = $recordsPerPage;
$this->currentPage = $currentPage;
}
public function getTotalPages() {
return ceil($this->totalRecords / $this->recordsPerPage);
}
public function getOffset() {
return ($this->currentPage - 1) * $this->recordsPerPage;
}
public function generatePageLinks() {
$totalPages = $this->getTotalPages();
$links = '';
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $this->currentPage) {
$links .= '<strong>' . $i . '</strong> ';
} else {
$links .= '<a href="?page=' . $i . '">' . $i . '</a> ';
}
}
return $links;
}
}
// 使用示例
$totalRecords = 100;
$recordsPerPage = 10;
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$pagination = new Pagination($totalRecords, $recordsPerPage, $currentPage);
$offset = $pagination->getOffset();
$pageLinks = $pagination->generatePageLinks();
// 輸出分頁(yè)鏈接
echo $pageLinks;
在上面的示例中,首先定義了一個(gè)Pagination類,該類包含了總記錄數(shù)、每頁(yè)記錄數(shù)和當(dāng)前頁(yè)碼等屬性,并提供了計(jì)算總頁(yè)數(shù)、獲取偏移量和生成分頁(yè)鏈接的方法。然后在使用示例中,根據(jù)用戶傳入的總記錄數(shù)、每頁(yè)記錄數(shù)和當(dāng)前頁(yè)碼,實(shí)例化Pagination類,并調(diào)用其中的方法生成分頁(yè)鏈接。最后將生成的分頁(yè)鏈接輸出到頁(yè)面上。
通過(guò)這種方式,可以簡(jiǎn)單的封裝和調(diào)用PHP分頁(yè)功能,實(shí)現(xiàn)分頁(yè)邏輯的復(fù)用和可維護(hù)性。