找回密码
 立即注册
搜索
查看: 1765|回复: 0

[面向对象] php面向对象子类中重载父类方法|重载与重写

[复制链接]

581

主题

110

回帖

4066

积分

管理员

积分
4066

众神之神

发表于 2016-1-11 13:42:03 | 显示全部楼层 |阅读模式
代码示例:
  1. <?php
  2. class person{
  3.     public $name;
  4.     public $age;
  5.     public $sex;

  6.     public function __construct($name, $age, $sex){
  7.         $this -> name = $name;
  8.         $this -> age = $age;
  9.         $this -> sex = $sex;
  10.     }

  11.     public function say(){
  12.         echo "我的名字是:{$this -> name},我的年龄是:{$this -> age},我的性别是:{$this -> sex}";
  13.     }
  14. }

  15. class teacher extends person{
  16.     public $teach;

  17.     public function __construct($name, $age, $sex, $teach){
  18.         parent::__construct($name, $age, $sex);
  19.         $this -> teach = $teach;
  20.     }

  21.     //重写:就是声明 一个与父类中同名的方法
  22.     public function say(){
  23.         //重载:parent::父类中的方法名
  24.         parent::say();
  25.         echo ",我教的学科是:{$this -> teach}";
  26.     }
  27. }

  28. class student extends person{
  29.     public $school;

  30.     public function __construct($name, $age, $sex, $school){
  31.         parent::__construct($name, $age, $sex);
  32.         $this -> school = $school;
  33.     }

  34.     public function say(){
  35.         parent::say();
  36.         echo ",我所在的学校是:{$this -> school}";
  37.     }
  38. }

  39. $teacher = new teacher("张三", 30, '男', '数学');
  40. $teacher -> say();

  41. echo "<hr />";
  42. $student = new student("李四", 18, '女', '北大');
  43. $student -> say();
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|十三博客 ( 鲁ICP备2023000528号 )

GMT+8, 2026-6-1 18:31 , Processed in 0.072575 second(s), 21 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表