PHP Interface Declaration: Syntax & Implementation
In PHP, the keyword ‘interface’ can be used to declare an interface. An interface is an abstract class that defines a set of methods without implementing them.
Here is an example demonstrating how to declare an interface in PHP.
<?php
// 声明一个接口
interface Shape {
public function calculateArea();
}
// 实现接口的类
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return M_PI * pow($this->radius, 2);
}
}
// 使用接口
$circle = new Circle(5);
echo 'Circle Area: ' . $circle->calculateArea();
In the example above, we declare an interface called Shape, which includes a method called calculateArea. We then create a class called Circle, and implement the calculateArea method from the Shape interface. Finally, we create a Circle object and call the calculateArea method to calculate the area of the circle.