介绍
接口是面向对象编程的重要功能,通过它可以指定要由类实现的方法,而不必定义应如何实现。
PHP通过interface关键字支持interface 。接口类似于类,但是方法没有定义主体。接口中的方法必须是公共的。实现这些方法的继承类必须使用Implements关键字而不是extends关键字定义,并且必须在父接口中提供所有方法的实现。
语法
<?php
interface testinterface{
public function testmethod();
}
class testclass implements testinterface{
public function testmethod(){
echo "implements interfce method";
}
}
?>
接口中的所有方法必须由实现类定义,否则PHP解析器将引发异常
示例
<?php
interface testinterface{
public function test1();
public function test2();
}
class testclass implements testinterface{
public function test1(){
echo "implements interface method";
}
}
$obj=new testclass()?>
输出结果
错误如下所示-
PHP Fatal error: Class testclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testinterface::test2)
可扩展的界面
就像普通的类一样,也可以使用extends关键字从中继承接口。
在下面的示例中,父类具有两个抽象方法,其中只有一个在子类中被重新定义。这导致错误如下-
示例
<?php
interface testinterface{
public function test1();
}
interface myinterface extends testinterface{
public function test2();
}
class testclass implements myinterface{
public function test1(){
echo "implements test1 method";
}
public function test2(){
echo "implements test2 method";
}
}
?>
使用接口的多重继承
PHP在extends子句中不允许使用多个类。但是,可以通过让子类实现一个或多个接口来实现多重继承。
在下面的示例中,myclass扩展了testclass并实现了testinterface以实现多重继承
示例
<?php
interface testinterface{
public function test1();
}
class testclass{
public function test2(){
echo "this is test2 function in parent class\n";
}
}
class myclass extends testclass implements testinterface{
public function test1(){
echo "implements test1 method\n";
}
}
$obj=new myclass();
$obj->test1();
$obj->test2();
?>
输出结果
这将产生以下输出-
implements test1 method this is test2 function in parent class
接口实例
示例
<?php
interface shape{
public function area();
}
class circle implements shape{
private $rad;
public function __construct(){
$this->rad=5;
}
public function area(){
echo "area of circle=" . M_PI*pow($this->rad,2) ."\n";
}
}
class rectangle implements shape{
private $width;
private $height;
public function __construct(){
$this->width=20;
$this->height=10;
}
public function area(){
echo "area of rectangle=" . $this->width*$this->height ."\n";
}
}
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
?>
输出结果
上面的脚本产生以下结果
area of circle=78.539816339745 area of rectangle=200




