How to Define and Implement Interfaces in PHP
In PHP object-oriented programming, interfaces play a crucial role in designing flexible and decoupled code. This article provides a clear, step-by-step guide on how to define an interface in PHP and how to implement it within a class, complete with practical code examples.
An interface is a contract that specifies which methods a class must
implement, without providing the actual implementation details. To
define an interface, use the interface keyword followed by
the interface name. Inside the interface, you declare public method
signatures without any curly braces or method bodies.
interface Logger {
public function log(string $message): void;
}To implement an interface, a class must use the
implements keyword in its declaration. The implementing
class is then required to define all the methods declared in the
interface. These methods must use the public visibility
modifier.
class FileLogger implements Logger {
public function log(string $message): void {
echo "Logging message to a file: " . $message;
}
}PHP also allows a single class to implement multiple interfaces. To
do this, separate the interface names with commas after the
implements keyword.
interface Serializable {
public function serialize(): string;
}
class DatabaseLogger implements Logger, Serializable {
public function log(string $message): void {
echo "Logging message to database: " . $message;
}
public function serialize(): string {
return serialize($this);
}
}By using interfaces, you can enforce consistency across different classes and write polymorphic code that depends on behaviors rather than specific class implementations.