浅谈类的继承特性

  类的继承在PHP这门弱类型的编程语言中,可以继承父类的所有属性和方法,包括构造方法。同时子类可以拥有自己独有的方法。extends为继承的关键词。parent::关键字可以调用父类中的成员方法和静态变量,而调用变量会出错。

  以下是代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
 5 <title>PHP数据库类</title>
 6 </head>
 7 
 8 <body>
 9 <?php 
10 /**********************
11 *内容:类的继承特性和覆盖父类的方法
12 *Author:瞎猫碰上死老虎
13 *Date:2/5/2015
14 *
15 **********************/
16 
17 class chem {
18     var $physicalChemistry='物理化学';
19     var $organicChemistry='有机化学';
20     var $analyticalChemistry='分析化学';
21     var $inorganicChemistry='无机化学';
22     
23     public function explain(){
24         echo '化学包括:'.$this->physicalChemistry.'&nbsp;&nbsp;'.$this->organicChemistry.'&nbsp;&nbsp;'.$this->analyticalChemistry.'&nbsp;&nbsp;'.$this->inorganicChemistry;
25         
26     }
27 }
28 
29 class mordernchem extends chem{
30     var $polymerChemistry='高分子化学';
31     public function rexplain(){
32         parent::explain(); //调用parent::访问父类方法
33     }
34     
35 }
36 
37 $chem1=new mordernchem;
38 echo "现代化学新增加的学科:".$chem1->polymerChemistry."<br/>";
39 $chem1->rexplain();
40 
41 
42 ?>
43 
44 </body>
45 </html>

结果为:

1 现代化学新增加的学科:高分子化学
2 化学包括:物理化学  有机化学  分析化学  无机化学
原文地址:https://www.cnblogs.com/soongkun/p/4274909.html