原文:http://hi.baidu.com/sheshi37c/blog/item/d28cdaf982521e53242df262.html
這樣的,我們前幾篇文章一直在說PHP接口的定義,相信你已經很熟悉了吧,好那 我們本篇就來講述接口的實現,一般都是定義一個類來實現接口,類通過使用implements來實現接口。這里要注意的是一個類可以使用 implements實現多個接口,但是類實現接口必須要實現其中的抽象方法。
下面就是一個接口被實現的小例子,代碼如下:
- <?php
- interface father{
- const NAME="zhen";
- function shuchu();
- function dayin($a);
- }
- class test implements father{
- function shuchu(){
- echo"接口被實例了";
- }
- function dayin($a){
- echo"我的名字是:".$a;
- }
- }
- $t=new test();
- $t->shuchu();
- echo"<br>";
- $t->dayin("zhenlw");
- ?>
示例運行結果如下:
接口被實例了 我的名字是:zhenlw |
看到上面的運行結果,我們知道了例子是正常的,但是如果你實現接口的時候沒有實現抽象方法,那就會報錯,哪怕沒有完全實例也會報錯,如下的例子所示:
- <?php
- interface father{
- const NAME="zhen";
- function shuchu();
- function dayin($a);
- }
- class test implements father{
- function dayin($a){
- echo"我的名字是:".$a;
- }
- }
- $t=new test();
- $t->dayin("zhenlw");
- ?>
示例運行結果如下:
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方法。