An interface in PHP defines a strict contract that classes must follow. It specifies method signatures without implementations and ensures consistency across different class implementations.
Interfaces are declared using the interface keyword. A class uses the implements keyword to follow the interface contract.
// Defining an interface with a required method
<?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");
?>
The FileLogger class implements the Logger interface and provides the required log() method. When executed, it prints a log message indicating the logging action.
Interface ➜ Implements ➜ Class ➜ Method Execution
PaymentGateway interface with a pay() methodPaypal and Stripe classes