原文: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方法。