学习PHP5的面向对象的编程方法,原来的这段面向过程的代码该如何修改?
原来在PHP4时代,一直采用面向过程的编程方法,这里举一个简单的例子,显示出员工信息。编码时采用了PHPLib的mysql操作类以及模板
类,因此程序页面文件分为show_staffinfo.php和show_staffinfo.html。代码如下
--------------show_staffinfo.php-----------------------
<?php
//引入phplib模板
include "../include/template.inc.php";
//数据库操作类
include "../include/db_mysql.inc.php";
$db=new DB_sql;
$db->connect();
$db->query("select id,name,telephone,address from staff");
//声明模板类。其中的参数是相对根目录的放模板文件的路径。
$t=new Template("template");
$t->set_file("show_staffinfo","show_staffinfo.html");
$t->set_block("show_staffinfo","row","rows");
while($db->next_record()) {
$t->set_var("name",$db->Record[name]);
$t->set_var("name",$db->Record[telephone]);
$t->set_var("name",$db->Record[address]);
$t->parse("rows","row",true);
}
$db->free();
//分析输出模板
$t->pparse("show_community","show_community");
?>
--------------template/show_staffinfo.html-----------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xhtml" >
<head>
<title>显示员工信息页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body background="#FFFFFF">
<table border="0" cellpadding="2" cellspacing="1" style="border-collapse: collapse" bordercolor="#111111" width="100%">
<tr>
<td width="20%">员工姓名</td>
<td width="20%">员工电话</td>
<td width="60%">家庭住址</td>
</tr>
<!-- BEGIN row -->
<tr>
<td>{name}</td>
<td>{telephone}</td>
<td>{address}</td>
</tr>
<!-- END row -->
</table>
</body>
</html>
最近本人在学习PHP5的面向对象的编程方法,一直想把原来的代码进行修改,但是因为PHP5不支持多重继承,不能同时继承PHPlib的mysql操作
类和模板类,因此给代码的修改工作造成了困难
以下是我以面向对象的方式修改了半截的代码
<?php
include "../include/template.inc.php";
include "../include/db_mysql.inc.php";
class ShowCommunityDB extends DB_sql {
function Show() {
$this->connect();
$this->query("select id,name,telephone,address from staff");
while($this->next_record()) {
echo $this->Record[name]."-".$this->Record[telephone]."-".$this->Record[address]."<br>";
}
$this->free();
}
}
$db=new ShowCommunityDB();
$db->Show();
?>
从上面的代码可以看到,我只能用echo $this->Record[name]."-".$this->Record[telephone]."-".$this->Record[address]."<br>";的简单
形式把数据显示出来,而不能想以前那样结合模板输出数据。请问大家如果我采用面向对象的编程方法,那么该如何修改我的代码呢?