interface, implements)An interface defines a strict contract of public methods that implementing classes must fulfill. Unlike abstract classes, a class can implement multiple interfaces, enabling true polymorphism and decoupled dependency injection.
| Feature | Abstract Class (abstract class) |
Interface (interface) |
|---|---|---|
| Multiple Inheritance | Single class inheritance (extends) |
Multiple interface implementation (implements A, B) |
| Properties | Supports member properties | Cannot contain instance properties |
| Method Implementation | Can contain concrete method bodies | Contains method signatures ONLY (PHP 8+) |
flowchart TD
A["interface LoggerInterface"] --> B["FileLogger implements LoggerInterface"]
A --> C["DatabaseLogger implements LoggerInterface"]
A --> D["CloudLogger implements LoggerInterface"]
E["Application Service"] -->|Type-hints contract| A
<?php
declare(strict_types=1);
interface NotifierInterface
{
public function sendNotification(string $recipient, string $message): bool;
}
interface LoggableInterface
{
public function getLogHeader(): string;
}
// Class implementing multiple interfaces
class EmailNotifier implements NotifierInterface, LoggableInterface
{
public function sendNotification(string $recipient, string $message): bool
{
echo "Sending Email to '$recipient': $message
";
return true;
}
public function getLogHeader(): string
{
return "[EMAIL_SERVICE]";
}
}
// Polymorphic Service dependent on Interface Contract
class UserRegistrationService
{
public function __construct(private NotifierInterface $notifier) {}
public function registerUser(string $email): void
{
// Business registration logic...
$this->notifier->sendNotification($email, "Welcome to our platform!");
}
}
$service = new UserRegistrationService(new EmailNotifier());
$service->registerUser("[email protected]");
Readable, Writable) over giant monolithic interfaces.implements for Contracts: Enable flexible mocking when writing automated unit tests.Write an interface CacheInterface with a method signature public function get(string $key): mixed;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.