Maison > Article > développement back-end > php开发之接口的使用
继承简化了对象,类的创建,增加了代码的可重性,但php只支持单继承,如果要实现多重继承,就要使用多个接口。
接口通过interface关键字来声明,并且类中只能包含未实现的方法和一些成员变量,格式如下:
interface interfaceName{
function interfaceName1();
function interfaceName2();
…
}
子类是通过implements关键字来实现接口的,如果要实现多个接口,那么每个接口之间应使用逗号“,”连接。而且所有未实现的方法都要在子类中实现,否则php将出错。格式如下:
class SubClass implments interfaceName1,interfaceName2{
function interfaceName1(){
//功能实现
}
function interfaceName2(){
//功能实现
}
}
示例代码如下:
<code><span><span><span><?php </span><span>//声明接口A</span><span><span>interface</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>;</span> } <span>//声明接口B</span><span><span>interface</span><span>B</span>{</span><span><span>function</span><span>Bb</span><span>()</span>;</span> } <span><span>class</span><span>Am</span><span>implements</span><span>A</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Aa is a php coder"</span>; } } <span><span>class</span><span>Bm</span><span>implements</span><span>A</span>,<span>B</span>{</span><span><span>function</span><span>Aa</span><span>()</span>{</span><span>echo</span><span>"Mike is a php coder<br>"</span>; <span>echo</span><span>"Mike is an ios coder<br>"</span>; } <span><span>function</span><span>Bb</span><span>()</span>{</span><span>echo</span><span>"Jack is a java coder"</span>; } } <span>$jack</span> =<span>new</span> Am(); <span>$bluce</span> =<span>new</span> Bm(); <span>$jack</span>->Aa(); <span>echo</span><span>"<br>"</span>; <span>$bluce</span>->Aa(); <span>$bluce</span>->Bb(); <span>?></span></span></span></span></code>
运行结果如下:
以上就介绍了php开发之接口的使用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。