继承特性简化了对象、类的创建,增加了代码的可重用性。但PHP只支持单继承,如果想实现多重继承,就要使用接口。PHP可以实现多个接口。
接口类通过interface关键字来声明,并且类中只能包含未实现的方法和一些成员变量。格式如下:
interface InterfaceName
{
function interfaceName1();
function interfaceName2();
...
}
注意:不要用public以外的关键字来修饰接口中的类成员,对于方法,不写关键字也可以。这是由接口类自身的特性决定的。
子类是通过implements关键字来实现接口的,如果要实现多个接口,那么每个接口之间使用逗号","连接,而且所有未实现的方法需要在子类中全部实现,否则PHP将会出现错误。格式如下:
class SubClass implements InterfaceName1, InterfaceName2
{
function interfaceName1(){
//功能实现
}
function interfaceName2(){
//功能实现
}
.....
}
例如:首先声明连个接口MPepedom和MPurview, 接着声明两个类Member和Manager,其中Member类继承了MPopedom接口,Manager继承了MPopedom和MPurview接口。分别实现各自成员方法后,实例化两个对象$member和$manager。最后调用实现后的方法,代码如下:
<?php
/*声明接口MPopedom*/
interface MPopedom
{
function popedom();
}
/*声明接口MPurview*/
interface MPurview
{
function purview();
}
/*创建子类Member,实现一个接口MPurview*/
class Member implements MPurview
{
function purview()
{
// TODO: Implement purview() method.
echo "会员拥有的权限";
}
}
/*创建子类Manager,实现多个接口MPurview和MPopedom*/
class Manager implements MPurview, MPopedom
{
function purview()
{
// TODO: Implement purview() method.
echo "管理员拥有会员的全部权限";
}
function popedom()
{
// TODO: Implement popedom() method.
echo "管理员还拥有会员没有的权限";
}
}
$member = new Member();//Member实例化
$manager = new Manager();//Manager实例化
$member->purview();//调用$member对象的purview方法
echo "<br>";
$manager->purview();//调用$manager对象的purview方法
$manager->popedom();//调用$manager对象的popedom方法
运行结果为:
会员拥有的权限
管理员拥有会员的全部权限管理员还拥有会员没有的权限
管理员拥有会员的全部权限管理员还拥有会员没有的权限
通过上面的实例,就可以发现,抽象类和接口实现的功能十分相似。抽象类的优点是可以在抽象类中实现公共的方法,而接口则可以实现多继承。什么时候用抽象类,什么时候使用接口,就要看具体实现了。