PHP基于面向对象封装的分页类示例

时间:2022-07-27
本文章向大家介绍PHP基于面向对象封装的分页类示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了PHP基于面向对象封装的分页类。分享给大家供大家参考,具体如下:

<?php
class Page
{
protected $num;//每页显示条数
protected $total;//总记录数
protected $pageCount;//总页数
protected $current;//当前页码
protected $offset;//偏移量
protected $limit;//分页页码
/**
* 构造方法
* @param int $total 总记录数
* @param int $num  每页显示条数
*/
public function __construct($total,$num=5)
{
//1.每页显示条数
$this- num = $num;
//2.总记录数
$this- total = $total;
//3.总页数
$this- pageCount = ceil($total/$num);
//4.偏移量
$this- offset = ($this- current-1)*$num;
//5.分页页码
$this- limit = "{$this- offset},{$this- num}";
//6.初始化当前页
$this- current();
}
/**
* 初始化当前页
*/
public function current(){
$this- current = isset($_GET['page'])?$_GET['page']:'1';
//判断当前页最大范围
if ($this- current $this- pageCount){
$this- current = $this- pageCount;
}
//判断当前页最小范围
if ($this- current<1){
$this- current = 1;
}
}
/**
* 访问没权限访问的属性
* @param string $key 想访问的属性
* @return float|int|string 返回对应要改变的条件
*/
public function __get($key){
if ($key == "limit") {
return $this- limit;
}
if ($key == "offset") {
return $this- offset;
}
if ($key == "current") {
return $this- current;
}
}
/**
* 处理分页按钮
* @return string 拼接好的分页按钮
*/
public function show(){
//判断初始页码
$_GET['page'] = isset($_GET['page'])?$_GET['page']:'1';
//将$_GET值赋给上下变量
$first = $end = $prev = $next = $_GET;
// var_dump($prev);
//上一页
//判断上一页范围
if ($this- current-1<1){
$prev['page'] = 1;
}else{
$prev['page'] = $this- current-1;
}
//下一页
//判断下一页范围
if ($this- current+1 $this- pageCount) {
$next["page"] = $this- pageCount;
}else{
$next['page'] = $this- current+1;
}
/*
首页
$first['page'] = 1; 
//尾页
$end['page'] = $this- pageCount;
*/
//拼接路径
$url = "http://".$_SERVER["SERVER_NAME"].$_SERVER["SCRIPT_NAME"];
//拼接数组url地址栏后缀?传入参数
//http://xxx/xxx/Page.class.php?page=值
$prev = http_build_query($prev);
$next = http_build_query($next);
// $first = http_build_query($first);
// $end = http_build_query($end);
//拼接完整路径
$prevpath = $url."?".$prev;
$nextpath = $url."?".$next;
// $firstpath = $url."?".$first;
// $endpath = $url."?".$end;
$str = "共有{$this- total}条记录 共有{$this- pageCount}页 ";
$str .= "<a href='{$url}?page=1' 首页</a  ";
$str .= "<a href='{$prevpath}' 上一页</a  ";
$str .= "<a href='{$nextpath}' 下一页</a  ";
$str .= "<a href='{$url}?page={$this- pageCount}' 尾页</a  ";
return $str;
}
}
//自行调试
$a = new Page(10);
echo $a- show();
? 

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP网络编程技巧总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。