以下是一个简单的PHP分页类的示例代码:
class Pagination {
private $totalPages;
private $currentPage;
private $perPage;
private $url;
public function __construct($totalPages, $currentPage, $perPage, $url) {
$this->totalPages = $totalPages;
$this->currentPage = $currentPage;
$this->perPage = $perPage;
$this->url = $url;
}
public function generateLinks() {
$links = '';
// 计算总页数
$totalPages = ceil($this->totalPages / $this->perPage);
// 生成上一页链接
if ($this->currentPage > 1) {
$prevPage = $this->currentPage - 1;
$links .= '<a href="' . $this->url . '?page=' . $prevPage . '">上一页</a> ';
}
// 生成页码链接
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $this->currentPage) {
$links .= $i . ' ';
} else {
$links .= '<a href="' . $this->url . '?page=' . $i . '">' . $i . '</a> ';
}
}
// 生成下一页链接
if ($this->currentPage < $totalPages) {
$nextPage = $this->currentPage + 1;
$links .= '<a href="' . $this->url . '?page=' . $nextPage . '">下一页</a>';
}
return $links;
}
}
// 使用示例
$totalPages = 10; // 总页数
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1; // 当前页码
$perPage = 5; // 每页显示数量
$url = 'example.php'; // 当前页面的URL
$pagination = new Pagination($totalPages, $currentPage, $perPage, $url);
$links = $pagination->generateLinks();
echo $links;
这个分页类接受总页数、当前页码、每页显示数量和当前页面的URL作为参数。它可以生成上一页、下一页和页码链接,并返回一个包含这些链接的字符串。使用示例中的代码,可以在页面中输出分页链接。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站