PHP 对象接口
简介
接口是面向对象编程的一个重要特性,它允许指定类需要实现的方法,而无需定义这些方法的具体实现方式。
PHP 通过 **interface** 关键字支持接口。接口类似于类,但其方法没有定义方法体。接口中的方法必须是 public 的。实现这些方法的继承类必须使用 **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
";
}
}
class myclass extends testclass implements testinterface{
public function test1(){
echo "implements test1 method
";
}
}
$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) ."
";
}
}
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 ."
";
}
}
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
?>输出
以上脚本产生以下结果
area of circle=78.539816339745 area of rectangle=200
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP