可扩展的PHP分页类

Posted by linyupark :: 2007,October 7th,11:06 am

网上的PHP分页类都有点年份久远了,还是自己写了一个,可以根据自己的需要继续在后面添加类型。

类文件(Page.php)

<?php 

	/*
	* 通用分页类,create by linyupark
	*/

	class Page
	{
		protected $page_size; //分页大小
		protected $rows_num;  //数据总数
		protected $pages;     //分页总数
		protected $page;      //当前页
		protected $url;       //分页地址
		protected $arg;       //分页参数变量

		function __construct($url,$arg,$page,$page_size,$rows_num)
		{
			$this->url = $url;
			$this->arg = $arg;
			$this->pages = ceil($rows_num/$page_size);
			if((int)$page > $this->pages) $this->page = $this->pages;
			if((int)$page < 1) $page = 1;
			$this->page = (int)$page;
			$this->page_size = $page_size;
			$this->rows_num = $rows_num;
		}

		#获取偏移量
		public function offset()
		{
			return ($this->page-1)*$this->page_size;
		}

		#仿搜索引擎
		public function spanNav($nav_span=5)
		{
			if($this->page <= $nav_span)
				$page_start = 1;
			else $page_start = $this->page - $nav_span;

			if($this->page + $nav_span < $this->pages)
				$page_end = $this->page + $nav_span;
			else $page_end = $this->pages;

			$nav = "";
			if($this->page!=1)
			{
				$pre_page = $this->page-1;
				$nav.= "<a href='{$this->url}?{$this->arg}=1'>第一页</a> | ";
				$nav.= "<a href='{$this->url}?{$this->arg}={$pre_page}'>前一页</a> | ";
			}
			for($i=$page_start;$i<=$page_end;$i++)
			{
				if($this->page == $i)
				$nav.= "<b>{$i}</b> | ";
				else
				$nav.= "<a href='{$this->url}?{$this->arg}={$i}'>{$i}</a> | ";
			}
			if($this->page!=$this->pages)
			{
				$nex_page = $this->page+1;
				$nav.= "<a href='{$this->url}?{$this->arg}={$nex_page}'>后一页</a> | ";
				$nav.= "<a href='{$this->url}?{$this->arg}={$this->pages}'>最后页</a>";
			}
			return $nav;
		}

		#下拉菜单型
		public function dropList()
		{
			$nav = "<select onchange=\"location.href='{$this->url}?{$this->arg}='+this.value;\">\n";
			for($i=1;$i<=$this->pages;$i++)
			{
				if($this->page == $i)
				$nav.= "<option value='{$i}' selected='selected'>第{$i}页</option>";
				else
				$nav.= "<option value='{$i}'>第{$i}页</option>";
			}
			$nav.= "</select>";
			return $nav;
		}
	}

?>

Leave a Reply