The interface Keyword
The keyword interface
is used to create interfaces - special constructs that define which methods a class must implement. Interfaces contain only method declarations without their implementation. A class that implements an interface must contain all methods declared in the interface.
Syntax
interface InterfaceName {
public function method1();
public function method2($param);
// ...
}
Example
Let's create a simple interface and a class that implements it:
<?php
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
echo "Logging to file: " . $message;
}
}
$logger = new FileLogger();
$logger->log("Test message");
?>
Code execution result:
'Logging to file: Test message'
Example
An interface can contain multiple methods, and a class must implement all of them:
<?php
interface Shape {
public function calculateArea();
public function calculatePerimeter();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return 3.14 * $this->radius * $this->radius;
}
public function calculatePerimeter() {
return 2 * 3.14 * $this->radius;
}
}
$circle = new Circle(5);
echo "Area: " . $circle->calculateArea();
?>
Code execution result:
'Area: 78.5'