PHP使用implements实现接口详解


原文:http://hi.baidu.com/sheshi37c/blog/item/d28cdaf982521e53242df262.html

这样的,我们前几篇文章一直在说PHP接口的定义,相信你已经很熟悉了吧,好那 我们本篇就来讲述接口的实现,一般都是定义一个类来实现接口,类通过使用implements来实现接口。这里要注意的是一个类可以使用 implements实现多个接口,但是类实现接口必须要实现其中的抽象方法。


下面就是一个接口被实现的小例子,代码如下:

 

  1. <?php
  2. interface father{
  3. const NAME="zhen";
  4. function shuchu();
  5. function dayin($a);
  6. }
  7. class test implements father{
  8. function shuchu(){
  9. echo"接口被实例了";
  10. }
  11. function dayin($a){
  12. echo"我的名字是:".$a;
  13. }
  14. }
  15. $t=new test();
  16. $t->shuchu();
  17. echo"<br>";
  18. $t->dayin("zhenlw");
  19. ?>


示例运行结果如下:

 

接口被实例了
我的名字是:zhenlw


看到上面的运行结果,我们知道了例子是正常的,但是如果你实现接口的时候没有实现抽象方法,那就会报错,哪怕没有完全实例也会报错,如下的例子所示:

 

  1. <?php
  2. interface father{
  3. const NAME="zhen";
  4. function shuchu();
  5. function dayin($a);
  6. }
  7. class test implements father{
  8. function dayin($a){
  9. echo"我的名字是:".$a;
  10. }
  11. }
  12. $t=new test();
  13. $t->dayin("zhenlw");
  14. ?>


示例运行结果如下:

 

Fatal error: Class test contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (father::shuchu) in D:\xampp\htdocs\test\8\test.php on line 13


这个错误的意思就是必须实例接口的shuchu方法。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM