抽象类允许类里面一部分方法不实现。抽象类介于接口和类之间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
//abstract用于定义抽象类 abstract class ACanEat { //在抽象方法前添加abstract关键字可以表明这个方法是抽象方法在这里不需要具体实现,继承的子类需要实现 abstract public function eat($food); //抽象类中可以包含普通的方法,在这里需要具体实现,这是公用方法,继承的子类不需要实现 public function breath(){ echo "Breath use the air. \n"; } } //继承抽象类的关键字是extends class Human extends ACanEat { //继承抽象类的子类需要实现抽象类中定义的抽象方法 public function eat($food){ echo "Human eating".$food."\n"; } } class Animal extends ACanEat { public function eat($food){ echo "Animal eating".$food."\n"; } } $man = new Human(); $man->eat('apple'); $man->breath(); //公用的 $monkey = new Animal(); $monkey->eat('banner'); $monkey->breath(); |
转载请注明:PHP笔记 » 抽象类abstract用法之PHP面向对象编程