以下是一个简单的PHP接口实例,展示了如何通过接口实现类与类的交互。

接口定义

我们定义一个接口`ShapeInterface`,该接口包含一个方法`getArea()`,用于计算形状的面积。

实例php使用接口,实例PHP使用接口:实现类与类的交互  第1张

```php

interface ShapeInterface {

public function getArea();

}

>

```

实现接口

然后,我们创建两个类`Circle`和`Rectangle`,它们都实现了`ShapeInterface`接口。

```php

class Circle implements ShapeInterface {

private $radius;

public function __construct($radius) {

$this->radius = $radius;

}

public function getArea() {

return pi() * $this->radius * $this->radius;

}

}

class Rectangle implements ShapeInterface {

private $width;

private $height;

public function __construct($width, $height) {

$this->width = $width;

$this->height = $height;

}

public function getArea() {

return $this->width * $this->height;

}

}

>

```

使用接口

现在,我们可以创建`Circle`和`Rectangle`类的实例,并通过`ShapeInterface`接口调用`getArea()`方法来计算它们的面积。

```php

$circle = new Circle(5);

$rectangle = new Rectangle(4, 6);

echo "