继承

 1 <?php
 2 
 3 class Human{
 4     public $name;
 5     public $height;
 6     public $weight;
 7 
 8     public function eat($food) {
 9         echo $this->name." is eating ".$food."<br/>";
10     }
11 }
12 
13 //php中可以使用extends关键字表示类的继承,后面跟父类的类名
14 //php中extends后面只能跟一个类的类名,这就是php的单继承原则
15 class NbaPlayer extends Human{
16     
17     public $team="Bull";
18     public $playerNumber="23";
19 
20     function __construct($name,$height,$weight,$team,$playerNumber) {
21         echo "In NbaPlayer constructor"."<br/>";
22         $this->name = $name;  //父类中的属性可以用this 来访问
23         $this->height = $height;
24         $this->weight = $weight;
25         $this->team = $team;
26         $this->playerNumber = $playerNumber;
27     }
28 
29     function __destruct() {
30         echo "Destroying".$this->name."<br/>";
31     }
32 
33     //方法定义
34     public function run() {
35         echo "Running"."<br/>";
36     }
37 
38     public function jump() {
39         echo "Jumping"."<br/>";
40     }
41     public function dribble() {
42         echo "Dribbling"."<br/>";
43     }
44     public function shoot() {
45         echo "shooting"."<br/>";
46     }
47     public function dunk() {
48         echo "Dunking"."<br/>";
49     }
50     public function pass() {
51         echo "passing"."<br/>";
52     }
53 }
54 
55 $jordan = new NbaPlayer("Jordan","198cm","98kg","Bull","23");
56 echo $jordan->name."<br/>";
57 
58 $jordan->eat("apple");//在子类的对象上可以直接访问父类的属性和方法

注意,在NbaPlayer()中是没有name,height,weight这些属性的,这些都是在父类中的属性,但通过继承后

可以成为子类NbaPlayer()中的属性

输出结果:

In NbaPlayer constructor
Jordan
Jordan is eating apple
DestroyingJordan

 

posted @ 2015-07-04 10:26  todaytoday  阅读(169)  评论(0编辑  收藏  举报