欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php 抽象类的简单应用

程序员文章站 2024-01-10 15:07:49
all right, 父类postparent定义为抽象,规定子类必须重新实现 buildhtml()方法,这个方法并没有花括号,如果有不管有没有内容都会报错的。 现在越看...
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;
}
}