What is Interface in PHP: Definition and Usage
interface is a way to define a contract for classes by specifying methods they must implement without providing the method bodies. It helps ensure different classes share the same method names and signatures, promoting consistent design and easier code management.How It Works
An interface in PHP acts like a promise or a blueprint that classes agree to follow. Imagine you have a set of rules for a game; every player must follow these rules to play correctly. Similarly, an interface lists method names and their expected inputs and outputs, but it does not say how these methods work inside.
When a class implements an interface, it must write the code for all the methods declared in that interface. This ensures that different classes can be used interchangeably if they follow the same interface, even if their internal workings differ. This is very useful when you want to write flexible and organized code.
Example
This example shows an interface called Logger with one method log. Two classes implement this interface, each providing its own way to log messages.
<?php
interface Logger {
public function log(string $message): void;
}
class FileLogger implements Logger {
public function log(string $message): void {
echo "Logging to a file: $message" . PHP_EOL;
}
}
class DatabaseLogger implements Logger {
public function log(string $message): void {
echo "Logging to a database: $message" . PHP_EOL;
}
}
$fileLogger = new FileLogger();
$fileLogger->log('File log entry');
$dbLogger = new DatabaseLogger();
$dbLogger->log('Database log entry');
When to Use
Use interfaces when you want to make sure different classes share the same set of methods, even if they do different things inside. This is helpful when you build large programs with many parts that need to work together smoothly.
For example, if you have different ways to save data (like saving to a file, database, or cloud), you can create an interface that all saving classes follow. This way, your program can switch between saving methods easily without changing other code.
Key Points
- An interface defines method names without code.
- Classes
implementinterfaces by writing the method code. - Interfaces help keep code organized and consistent.
- They allow different classes to be used interchangeably.