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