In PHP, an interface is a contract that defines a set of methods that a class must implement. It provides a way to specify what methods a class should have without providing the implementation. Classes can then implement one or more interfaces, guaranteeing that they provide the required functionality. An interface in PHP is declared using the interface keyword.
interface InterfaceName {
public function method1();
public function method2($param);
// More method declarations...
}
To implement an interface, a class uses the implements keyword and provides concrete implementations for all the methods declared in the interface.
class ClassName implements InterfaceName {
// Implement all methods declared in InterfaceName
public function method1() {
// Implementation
}
public function method2($param) {
// Implementation
}
// More methods...
}
Example of an Interface:
Here's an example to illustrate how interfaces work in PHP:
// Define an interface
interface Shape {
public function getArea();
}
// Implement the interface in classes
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
// Creating objects of classes implementing the interface
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
// Calling getArea() on the objects
echo "Area of Circle: {$circle->getArea()}<br>"; // Output: Area of Circle: 78.53975
echo "Area of Rectangle: {$rectangle->getArea()}<br>"; // Output: Area of Rectangle: 24
In this example:
A class can implement multiple interfaces by separating them with commas in the implements clause.
interface Interface1 {
public function method1();
}
interface Interface2 {
public function method2();
}
class MyClass implements Interface1, Interface2 {
public function method1() {
// Implementation
}
public function method2() {
// Implementation
}
}
Interfaces can also contain constants, which are automatically public, static, and final.
interface MyInterface {
const MY_CONSTANT = 123;
}
// Accessing interface constants
echo MyInterface::MY_CONSTANT; // Output: 123
Interfaces can also extend other interfaces, allowing for the creation of a hierarchy of interfaces.
interface Interface1 {
public function method1();
}
interface Interface2 extends Interface1 {
public function method2();
}
Interface:
Abstract Class:
Interfaces in PHP provide a way to define a contract that classes must follow by declaring a set of method signatures. Classes can then implement one or more interfaces, guaranteeing that they provide the required functionality. Interfaces are useful for defining a common API that multiple classes can adhere to, promoting code reusability and maintainability.