- 抽象类:含有抽象方法的类【abstract 抽象关键词】
1 abstract class Usb 2 { 3 public function load(){ 4 echo "
Usb is loading
"; 5 } 6 7 public function start(){ 8 echo "Usb is starting
"; 9 }10 11 # 抽象方法12 abstract public function unload();13 }14 15 # 子类16 class Upan extends Usb17 {18 # 调用需先实现unload抽象方法19 public function unload(){20 echo "Usb is unloading
";21 }22 23 public function jitui(){24 echo "我喜欢鸡腿
";25 }26 }27 28 $obj = new Upan();29 $obj->load(); - 接口:只含有抽象方法的类【interface、abstract 抽象关键词】
1 interface Usb 2 { 3 public function load(); 4 5 public function start(); 6 7 public function unload(); 8 } 9 10 # 子类11 class Upan implements Usb12 {13 public function load(){14 echo "
Usb is loading
";15 }16 17 public function start(){18 echo "Usb is starting
";19 }20 21 public function unload(){22 echo "Usb is unloading
";23 }24 }25 26 # 调用前需全部实现Usb类中的抽象方法27 $obj = new Upan();28 $obj->load(); - 一个子类实现多个接口
1 interface Usb 2 { 3 public function load(); 4 5 public function start(); 6 7 public function unload(); 8 } 9 10 interface Usb211 {12 public function run();13 }14 15 # 子类16 class Upan implements Usb,Usb217 {18 public function load(){19 echo "
Usb is loading
";20 }21 22 public function start(){23 echo "Usb is starting
";24 }25 26 public function unload(){27 echo "Usb is unloading
";28 }29 30 public function run(){31 echo "Usb2 is runing
";32 }33 }34 35 $obj = new Upan();36 $obj->load(); - 接口扩展,只能继承不能实现,一般不常用
1 interface Usb 2 { 3 public function load(); 4 5 public function start(); 6 7 public function unload(); 8 } 9 10 interface Usb2 extends Usb11 {12 public function run();13 }14 15 # 子类16 class Upan implements Usb217 {18 public function load(){19 echo "
Usb is loading
";20 }21 22 public function start(){23 echo "Usb is starting
";24 }25 26 public function unload(){27 echo "Usb is unloading
";28 }29 30 public function run(){31 echo "Usb2 is runing
";32 }33 }34 35 $obj = new Upan();36 $obj->load(); - 多态小实例
1 interface Usb 2 { 3 public function load(); 4 5 public function start(); 6 7 public function unload(); 8 } 9 10 # 子类11 class Upan implements Usb12 {13 public function load(){14 echo "
Usb is loading
";15 }16 17 public function start(){18 echo "Usb is starting
";19 }20 21 public function unload(){22 echo "Usb is unloading
";23 }24 25 public function run(){26 echo "Usb2 is runing
";27 }28 }29 30 # 非法类31 class Udisk32 {33 public function load(){34 echo "Usb is loading
";35 }36 37 public function start(){38 echo "Usb is starting
";39 }40 41 public function unload(){42 echo "Usb is unloading
";43 }44 }45 46 # 只有实现了Usb接口中所有方法才能正常调用47 function useUsb(Usb $o){48 $o->load();49 $o->start();50 $o->unload();51 echo "
";52 }53 54 $obj = new Upan();55 $obj2 = new Udisk();56 useUsb($obj);57 useUsb($obj2); #失败