php入门教程(四)类的使用
2019-10-11 本文已影响0人
党云龙
有话说在前面
php中类是非常重要的,说实话,你只要理解了类,你就可以完成大部分的php操作,因为就算你自己不会写,你也可以引入其他人写的类。就跟你在js中引入了什么swiper之类的东西一样。
一开始我们都不会写,都是调其他人写的,这就是一个同样的道理。
请看基本的例子
//1
//创建类并返回初始值
//注意这里属于类的$this的属性是无需使用$的,直接返回$this ->name即可
class yunlong{
public $name = '党云龙';
function getName(){
return $this -> name;
}
}
$man = new yunlong();
echo $man -> getName();
//2
class dang{
public $age1 = 30;
private $age2 = 31;
static $age3 = 32;
function getAge(){
return $this -> age2 + 20;
}
function badFun(){
//注意 :: 只能访问静态变量,不能访问public和private
return dang::$age3;
}
}
$test = new dang();
echo $test -> badFun();
这里又涉及到了一个非常重要的概念。
我们不可能每个类都去自己写,我们大部分时候只是写一些简单的逻辑变量方法等。
那么我们要怎么引入其他人写的类呢?
使用这个语法:
include("phpName.php");
加载后如何使用呢?
使用别人写好的类,我们可以快速创建应用
[图片上传中...(image.png-29c42a-1570618391836-0)]
请看我这个php分页例子:
<?php
$data = array(
array("id"=>1,"title"=>"标题1"),
array("id"=>2,"title"=>"标题2"),
array("id"=>3,"title"=>"标题3"),
array("id"=>4,"title"=>"标题4"),
array("id"=>5,"title"=>"标题5"),
array("id"=>6,"title"=>"标题6"),
array("id"=>7,"title"=>"标题7"),
array("id"=>8,"title"=>"标题8"),
array("id"=>9,"title"=>"标题9"),
array("id"=>10,"title"=>"标题10"),
array("id"=>11,"title"=>"标题11"),
array("id"=>12,"title"=>"标题12"),
array("id"=>13,"title"=>"标题13"),
array("id"=>14,"title"=>"标题14"),
array("id"=>15,"title"=>"标题15"),
array("id"=>16,"title"=>"标题16"),
array("id"=>17,"title"=>"标题17"),
array("id"=>18,"title"=>"标题18"),
array("id"=>19,"title"=>"标题19"),
array("id"=>20,"title"=>"标题20"),
array("id"=>21,"title"=>"标题21"),
array("id"=>22,"title"=>"标题22"),
);
//设置编码类型为utf-8;
Header("Content-Type:text/html;charset=utf-8");
//var_dump($data)//输出内容和类型
$pageall = count($data); //总条数
$pageNum = 5; //每页显示多少个
$thispage = isset($_GET['page']) ? $_GET['page'] : 1;//获取当前访问的页码 isset检测变量是否存在
$pageurl = '4.php?page=(:num)';//页面的url
//引入别人写好的分页类
include("page.php");
//创建分页
//需要传入 1.总数 2.每页显示条数 3.当前访问的页码 4.页面的url
$paginator = new Paginator($pageall,$pageNum,$thispage,$pageurl);
//查找元素位置 每次我们页面上只渲染5个,所以你需要每次把需要渲染的这个5个找出来
//array_splice(array,start,length,array) 从开始为位置指定一个数量开始截取,并且返回一个新数组
$getdata = array_splice($data,($thispage-1)*$pageNum,$pageNum);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf=8">
<title>php分页例子</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body class="container bg-info">
<div>
<h3>php分页例子</h3>
<ul>
<?php foreach($getdata as $vo){?>
<li>
<?php echo $vo['title']?>
</li>
<?php }?>
</ul>
</div>
<?php echo $paginator ?>
</body>
</html>
可能你突然看到这么一大片代码有点懵,没关系,这里面只有最基本的逻辑,
你仔细看就会发现我们其实只用到了,总页数,每页显示多少个,当前获取的那一页,和页面url这四个东西。
其实你仔细思考一下,跟你在vue中需要知道的那几个几乎都是一样的。
其他的东西,类的作者已经都帮我们写好了。所以当你遇到不会的东西的时候,直接从网上搜一个别人写好的类是最好的办法。
最后附上我这个类的写法:
<?php
//namespace JasonGrimes;
class Paginator {
const NUM_PLACEHOLDER = '(:num)';
protected $totalItems;
protected $numPages;
protected $itemsPerPage;
protected $currentPage;
protected $urlPattern;
protected $maxPagesToShow = 10;
protected $previousText = '上一页';
protected $nextText = '下一页';
/**
* @param int $totalItems The total number of items.
* @param int $itemsPerPage The number of items per page.
* @param int $currentPage The current page number.
* @param string $urlPattern A URL for each page, with (:num) as a placeholder for the page number. Ex. '/foo/page/(:num)'
*/
public function __construct($totalItems, $itemsPerPage, $currentPage, $urlPattern = '')
{
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
$this->urlPattern = $urlPattern;
$this->updateNumPages();
}
protected function updateNumPages()
{
$this->numPages = ($this->itemsPerPage == 0 ? 0 : (int) ceil($this->totalItems/$this->itemsPerPage));
}
/**
* @param int $maxPagesToShow
* @throws \InvalidArgumentException if $maxPagesToShow is less than 3.
*/
public function setMaxPagesToShow($maxPagesToShow)
{
if ($maxPagesToShow < 3) {
throw new \InvalidArgumentException('maxPagesToShow cannot be less than 3.');
}
$this->maxPagesToShow = $maxPagesToShow;
}
/**
* @return int
*/
public function getMaxPagesToShow()
{
return $this->maxPagesToShow;
}
/**
* @param int $currentPage
*/
public function setCurrentPage($currentPage)
{
$this->currentPage = $currentPage;
}
/**
* @return int
*/
public function getCurrentPage()
{
return $this->currentPage;
}
/**
* @param int $itemsPerPage
*/
public function setItemsPerPage($itemsPerPage)
{
$this->itemsPerPage = $itemsPerPage;
$this->updateNumPages();
}
/**
* @return int
*/
public function getItemsPerPage()
{
return $this->itemsPerPage;
}
/**
* @param int $totalItems
*/
public function setTotalItems($totalItems)
{
$this->totalItems = $totalItems;
$this->updateNumPages();
}
/**
* @return int
*/
public function getTotalItems()
{
return $this->totalItems;
}
/**
* @return int
*/
public function getNumPages()
{
return $this->numPages;
}
/**
* @param string $urlPattern
*/
public function setUrlPattern($urlPattern)
{
$this->urlPattern = $urlPattern;
}
/**
* @return string
*/
public function getUrlPattern()
{
return $this->urlPattern;
}
/**
* @param int $pageNum
* @return string
*/
public function getPageUrl($pageNum)
{
return str_replace(self::NUM_PLACEHOLDER, $pageNum, $this->urlPattern);
}
public function getNextPage()
{
if ($this->currentPage < $this->numPages) {
return $this->currentPage + 1;
}
return null;
}
public function getPrevPage()
{
if ($this->currentPage > 1) {
return $this->currentPage - 1;
}
return null;
}
public function getNextUrl()
{
if (!$this->getNextPage()) {
return null;
}
return $this->getPageUrl($this->getNextPage());
}
/**
* @return string|null
*/
public function getPrevUrl()
{
if (!$this->getPrevPage()) {
return null;
}
return $this->getPageUrl($this->getPrevPage());
}
/**
* Get an array of paginated page data.
*
* Example:
* array(
* array ('num' => 1, 'url' => '/example/page/1', 'isCurrent' => false),
* array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
* array ('num' => 3, 'url' => '/example/page/3', 'isCurrent' => false),
* array ('num' => 4, 'url' => '/example/page/4', 'isCurrent' => true ),
* array ('num' => 5, 'url' => '/example/page/5', 'isCurrent' => false),
* array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
* array ('num' => 10, 'url' => '/example/page/10', 'isCurrent' => false),
* )
*
* @return array
*/
public function getPages()
{
$pages = array();
if ($this->numPages <= 1) {
return array();
}
if ($this->numPages <= $this->maxPagesToShow) {
for ($i = 1; $i <= $this->numPages; $i++) {
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
} else {
// Determine the sliding range, centered around the current page.
$numAdjacents = (int) floor(($this->maxPagesToShow - 3) / 2);
if ($this->currentPage + $numAdjacents > $this->numPages) {
$slidingStart = $this->numPages - $this->maxPagesToShow + 2;
} else {
$slidingStart = $this->currentPage - $numAdjacents;
}
if ($slidingStart < 2) $slidingStart = 2;
$slidingEnd = $slidingStart + $this->maxPagesToShow - 3;
if ($slidingEnd >= $this->numPages) $slidingEnd = $this->numPages - 1;
// Build the list of pages.
$pages[] = $this->createPage(1, $this->currentPage == 1);
if ($slidingStart > 2) {
$pages[] = $this->createPageEllipsis();
}
for ($i = $slidingStart; $i <= $slidingEnd; $i++) {
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
if ($slidingEnd < $this->numPages - 1) {
$pages[] = $this->createPageEllipsis();
}
$pages[] = $this->createPage($this->numPages, $this->currentPage == $this->numPages);
}
return $pages;
}
/**
* Create a page data structure.
*
* @param int $pageNum
* @param bool $isCurrent
* @return Array
*/
protected function createPage($pageNum, $isCurrent = false)
{
return array(
'num' => $pageNum,
'url' => $this->getPageUrl($pageNum),
'isCurrent' => $isCurrent,
);
}
/**
* @return array
*/
protected function createPageEllipsis()
{
return array(
'num' => '...',
'url' => null,
'isCurrent' => false,
);
}
/**
* Render an HTML pagination control.
*
* @return string
*/
public function toHtml()
{
if ($this->numPages <= 1) {
return '';
}
$html = '<ul class="pagination">';
if ($this->getPrevUrl()) {
$html .= '<li><a href="' . htmlspecialchars($this->getPrevUrl()) . '">« '. $this->previousText .'</a></li>';
}
foreach ($this->getPages() as $page) {
if ($page['url']) {
$html .= '<li' . ($page['isCurrent'] ? ' class="active"' : '') . '><a href="' . htmlspecialchars($page['url']) . '">' . htmlspecialchars($page['num']) . '</a></li>';
} else {
$html .= '<li class="disabled"><span>' . htmlspecialchars($page['num']) . '</span></li>';
}
}
if ($this->getNextUrl()) {
$html .= '<li><a href="' . htmlspecialchars($this->getNextUrl()) . '">'. $this->nextText .' »</a></li>';
}
$html .= '</ul>';
return $html;
}
public function __toString()
{
return $this->toHtml();
}
public function getCurrentPageFirstItem()
{
$first = ($this->currentPage - 1) * $this->itemsPerPage + 1;
if ($first > $this->totalItems) {
return null;
}
return $first;
}
public function getCurrentPageLastItem()
{
$first = $this->getCurrentPageFirstItem();
if ($first === null) {
return null;
}
$last = $first + $this->itemsPerPage - 1;
if ($last > $this->totalItems) {
return $this->totalItems;
}
return $last;
}
public function setPreviousText($text)
{
$this->previousText = $text;
return $this;
}
public function setNextText($text)
{
$this->nextText = $text;
return $this;
}
}
小贴士
这里有一个很有意思的东西,就是你看到的别人写的类。
只有一个<?php的开始标签,却没有结束标签这是为什么呢?因为当你的php页面中如果嵌入了html,就必须有结束标签,如果没有嵌入,而是一个纯粹的php,那么就没有必要写结束符号?>