php 抽象类的简单应用

yipeiwu_com5年前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;
}
}

相关文章

php 查找数组元素提高效率的方法详解

1.php in_array方法说明 PHP查找数组元素是否存在,一般会使用in_array方法。 bool in_array ( mixed $needle , array $hays...

学习PHP session的传递方式

学习PHP session的传递方式

本文实例为大家分享了PHP session的三种传递方式,供大家参考,具体内容如下 既然学习到了就做下笔记,解决数据的共享,在也不要担心,什么时候还要你自己手动去设置打开cookie了!...

PHP面向对象程序设计之对象的遍历操作示例

本文实例讲述了PHP面向对象程序设计之对象的遍历操作。分享给大家供大家参考,具体如下: 对象的遍历和数组的遍历一样,对象的遍历指的是实例属性的遍历。 下面遍历出来的属性,是在该范围中的...

PHP排序算法之直接插入排序(Straight Insertion Sort)实例分析

本文实例讲述了PHP排序算法之直接插入排序(Straight Insertion Sort)。分享给大家供大家参考,具体如下: 算法引入: 在这里我们依然使用《大话数据结构》里面的一个例...

php实现的中秋博饼游戏之绘制骰子图案功能示例

php实现的中秋博饼游戏之绘制骰子图案功能示例

本文实例讲述了php实现的中秋博饼游戏之绘制骰子图案功能。分享给大家供大家参考,具体如下: 最近公司中秋博饼(在厦门),自己没事也想玩玩,所以就想动手写了一个纯php实现的中秋博饼游戏,...