【PHP开发】深入浅出理解PHP分页原理与面向对象封装模块功能实现《附完整版代码》
<?php
class Pagination {
private $current_page;
private $per_page_record;
private $total_records;
private $total_pages;
private $url;
function __construct($total_records, $current_page, $url, $per_page_record = 10) {
$this->total_records = $total_records;
$this->current_page = $current_page;
$this->url = $url;
$this->per_page_record = $per_page_record;
$this->total_pages = ceil($total_records / $per_page_record);
}
function createLinks() {
$html = '';
if ($this->current_page > 1) {
$previous = $this->current_page - 1;
$html .= "<a href='{$this->url}page={$previous}'>Previous</a>";
}
for ($x = max(1, $this->current_page - 2); $x <= min($this->total_pages, $this->current_page + 2); $x++) {
if ($x == $this->current_page) {
$html .= "{$x}";
} else {
$html .= "<a href='{$this->url}page={$x}'>{$x}</a>";
}
}
if ($this->current_page < $this->total_pages) {
$next = $this->current_page + 1;
$html .= "<a href='{$this->url}page={$next}'>Next</a>";
}
return $html;
}
}
// 使用示例
$total_records = 100; // 假设总共有100条记录
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$url = 'http://example.com/page='; // 分页链接的基础URL
$pagination = new Pagination($total_records, $current_page, $url);
echo $pagination->createLinks();
这段代码实现了一个简单的分页类,可以用来生成分页导航链接。类中定义了构造函数、属性和方法,方法中包含了计算总页数、创建分页链接的逻辑。使用时,只需实例化该类,并调用createLinks
方法即可生成分页导航。
评论已关闭