How to Implement Interface in PHP: Syntax and Example
In PHP, you implement an
interface by using the implements keyword in a class definition. The class must then define all methods declared in the interface with the exact signatures.Syntax
An interface defines method signatures without implementation. A class uses the implements keyword to promise it will provide all those methods.
- interface InterfaceName: declares the interface.
- public function methodName();: method signature in the interface.
- class ClassName implements InterfaceName: class that implements the interface.
- The class must define all interface methods exactly.
php
<?php
interface Logger {
public function log(string $message);
}
class FileLogger implements Logger {
public function log(string $message) {
echo "Logging message: $message";
}
}
Example
This example shows an interface Logger with one method log. The class FileLogger implements the interface and defines the log method to print a message.
php
<?php
interface Logger {
public function log(string $message);
}
class FileLogger implements Logger {
public function log(string $message) {
echo "Logging message: $message";
}
}
$logger = new FileLogger();
$logger->log("Hello World!");
Output
Logging message: Hello World!
Common Pitfalls
Common mistakes when implementing interfaces in PHP include:
- Not implementing all methods declared in the interface causes a fatal error.
- Changing method signatures (like parameter types or return types) in the class is not allowed.
- Trying to instantiate an interface directly is invalid.
Always ensure your class fully matches the interface method signatures.
php
<?php
interface Logger {
public function log(string $message);
}
// Wrong: Missing method implementation
// class BrokenLogger implements Logger {
// }
// Correct implementation
class FixedLogger implements Logger {
public function log(string $message) {
echo $message;
}
}
Quick Reference
| Concept | Description |
|---|---|
| interface | Defines method signatures without code |
| implements | Keyword used by class to adopt interface |
| Method signatures | Must match exactly in class |
| Cannot instantiate | Interfaces cannot be created directly |
| Multiple interfaces | Class can implement multiple interfaces separated by commas |
Key Takeaways
Use the implements keyword in a class to adopt an interface.
Define all methods declared in the interface exactly in your class.
Interfaces cannot be instantiated directly.
Method signatures in the class must match the interface exactly.
A class can implement multiple interfaces separated by commas.