使用parent:: 來調用父類中的方法
例子:
1 <?php 2 class EMBA_student // 聲明EMBA學生類 3 { 4 //用var來定義類的屬性 5 var $no; //序號 6 var $name; // 姓名 7 var $gender; //性別 8 var $age; //年齡 9 10 //方法 11 //方法1 ,設定學生的信息方法 12 function set_data ($arr) 13 { 14 $this->no=$arr["no"]; 15 $this->name=$arr["name"]; 16 $this->gender=$arr["gender"]; 17 $this->age=$arr["age"]; 18 } 19 // 方法2, 讓學生年齡長大$i歲 20 function set_grow($i) 21 { 22 $this->age+=$i; 23 } 24 //方法3 ,輸出學生信息的方法 25 function get_data() 26 { 27 echo "<br /> 28 <b>長江商學院EMBA班學生信息</b><br /> 29 "; 30 31 echo"學號:$this->no<br />"; 32 echo"姓名:$this->name<br />"; 33 echo"性別:$this->gender<br />"; 34 echo"年齡:$this->age<br />"; 35 36 } 37 } 38 // 繼承EMBA學生類,來創建一個EMBA方向類 39 class college_student extends EMBA_student{ 40 var $department; //定義一個新的屬性所在系 41 //重載父類的方法,設定學員的信息 42 function set_data($arr) 43 { 44 parent::set_data($arr); 45 $this->department=$arr["department"]; 46 } 47 function change_department($new_department) //定義一個新的方法,更換所在系 48 { 49 $this->department=$new_department; //讓學員所在系變成參數系 50 } 51 //輸出學生的信息 52 function get_data(){ 53 parent::get_data(); 54 echo"學習方向:$this->department<br />"; 55 } 56 57 } 58 //實例化一個對象 59 $s=new college_student; 60 $arr=array("no"=>"1","name"=>"Qian Zhang","gender"=>"Female","age"=>"33","department"=>"商業營銷"); 61 $s->set_data($arr); 62 $s->get_data(); 63 64 65 66 ?>
結果:
長江商學院EMBA班學生信息
學號:1
姓名:Qian Zhang
性別:Female
年齡:33
學習方向:商業營銷