zoukankan      html  css  js  c++  java
  • 继承

     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
  • 相关阅读:
    Eclipse
    文件递归查找
    BeanFactory 和 AppliactionContext的区别?
    文件上传
    Servlet路径的使用
    FileInputStream和FileOutputStream文件复制
    CentOS 7安装Nginx
    C语言程序设计100例之(6):数字反转
    C语言程序设计100例之(5):分解质因数
    C语言程序设计100例之(4):水仙花数
  • 原文地址:https://www.cnblogs.com/jacson/p/4620285.html
Copyright © 2011-2022 走看看