类的继承的应用

  1. PHP只支持单继承,一个子类只能有一个父类。一个父类可以被多个子类继承。<br /> 它支持多重继承,b继承ac继承b,那么c也就间接继承了a
  1. <?php
  2. class A
  3. {
  4. }
  5. class B extends A
  6. {
  7. }


访问类型控制

访问权限

关键字 同一类中 子类中 类外部
public 可以 可以 可以
private 可以 不可以 不可以
protected 可以 可以 不可以

子类中重载父类的方法

  1. 比如父类定义了一个方法,子类可以对这个方法重写和重载。<br /> 重载就是方法名还是一样,但是参数不一样。<br /> 重写就是方法名不变,原来的方法就没有了。<br /> 父类定义了一个a,但是不一定在执行的时候是被重写了还是重载了,这种多种多样的状态,就叫多态。

继承


  1. <?php
  2. class Person
  3. {
  4. public $name;
  5. private $age;
  6. protected $money;
  7. public function __construct($name, $age, $money)
  8. {
  9. $this->name = $name;
  10. $this->age = $age;
  11. $this->money = $money;
  12. }
  13. public function info()
  14. {
  15. echo $this->name, $this->age, $this->money;
  16. }
  17. }
  18. class Yellow extends Person
  19. {
  20. public function person()
  21. {
  22. echo $this->name, $this->age, $this->money;
  23. }
  24. }
  25. $p = new Yellow("li", 30, 100);
  26. $p->info();
  27. $p->person();

此时页面会输出 li 30 100和 age 未定义。因为 Yellow 继承类父类,所以可以拿到父类里的公有方法,去执行的时候相当于执行了 父类的 __construct 和 info 方法。所以执行info不但不会报错,还会正常输出。
但是执行子类非继承的公有方法时,因为父类的 age 属性是私有的,所以子类是无法继承的。这样就会告诉我们age没有定义。

重写


  1. <?php
  2. class Person
  3. {
  4. public $name;
  5. private $age;
  6. protected $money;
  7. public function __construct($name, $age, $money)
  8. {
  9. $this->name = $name;
  10. $this->age = $age;
  11. $this->money = $money;
  12. }
  13. public function info()
  14. {
  15. echo $this->name, $this->age, $this->money;
  16. }
  17. }
  18. class Yellow extends Person
  19. {
  20. public function info($name)
  21. {
  22. echo $name;
  23. }
  24. }
  25. $p = new Yellow("li", 30, 100);
  26. $p->info("Lc");

上面代码会输出Lc 以及一个警告:子类的方法与父类的方法重名了。这说因为首先子类继承了父类的方法,但是又写类一个与父类重名的方法,那么子类的就会覆盖父类的。这样的方式叫重写。


重载

  1. <?php
  2. class Person
  3. {
  4. public $name;
  5. private $age;
  6. protected $money;
  7. public function __construct($name, $age, $money)
  8. {
  9. $this->name = $name;
  10. $this->age = $age;
  11. $this->money = $money;
  12. }
  13. public function info()
  14. {
  15. echo $this->name, $this->age, $this->money;
  16. }
  17. }
  18. class Yellow extends Person
  19. {
  20. public function info($name)
  21. {
  22. parent::info();
  23. echo $name;
  24. }
  25. }
  26. $p = new Yellow("li", 30, 100);
  27. $p->info(123);

上面代码会首先输出 li, 30, 100 然后 123。还有一个警告。通过parent:: 可以实现父类方法的重载。等于两个方法都执行。