程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php 抽象類的簡單應用

php 抽象類的簡單應用

編輯:關於PHP編程

All right, 父類postParent定義為抽象,規定子類必須重新實現 buildHTML()方法,這個方法並沒有花括號,如果有不管有沒有內容都會報錯的。
現在越看越覺得這代碼完全沒必要用抽象類,用繼承也都很雞肋,好吧,也沒啥好說的好像。。。。。
另外我把mysql 分開在外面了,所以調用方法很麻煩
1,先實例化 readArticle
2,mysql查詢,參數來自 readArticle::getSQL();
3,返回mysql結果資源給 readArticle::fetchResult( $result );
4,readArticle::buildHTML(); 返回HTML
如果是列表循環輸出的話,把 3 和 4 重復調用就可以了
復制代碼 代碼如下:
abstract class postParent
{
protected $querySQL;
public $fetchResult;
public $timeAgo; // eg : 2 days ago
abstract protected function buildHTML();
public function getSQL()
{
return $this->querySQL;
}
public function fetchResult( $result )
{
$this->fetchResult = mysql_fetch_assoc( $result );
}
public function error()
{}
}
class readArticle extends postParent
{
public function __construct( $id )
{
$this->querySQL =<<<eof
SELECT title, author, text, unixtime FROM post
WHERE id = $id ORDER BY unixtime DESC;
eof;
}
public function buildHTML()
{
return <<<eof
<div id="post-text">
<div class="post-title-div">
<h4>
<a href="http://foodstory.me/post.php?id={$this->fetchResult['id']}"
class="post-title-a" > {$this->fetchResult['title']}
</a>
</h4>
</div>
<div class="post-info-div">
<span class='post-info-author'>{$this->fetchResult['author']}</span> at
<time class='post-info-time'>{$this->timeAgo}</time>
</div>
<div class="post-p-div">
{$this->fetchResult['text']}
</div>
</div>
eof;
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved