A PHP interface defines a strict list of public methods that any implementing class promises to provide, without dictating how those methods work internally. Interfaces enable polymorphism and dependency injection, letting you swap a real email sender or payment API for a fake test version without touching caller code.
Declare an interface with interface and attach it to classes with implements. A single class can implement multiple interfaces separated by commas (implements MailerInterface, LoggableInterface).
classDiagram
class MailerInterface {
<<interface>>
+send(string to, string subject) bool
}
class SmtpMailer {
+send(string to, string subject) bool
}
class ArrayTestMailer {
+send(string to, string subject) bool
}
MailerInterface <|.. SmtpMailer : implements
MailerInterface <|.. ArrayTestMailer : implements
<?php
declare(strict_types=1);
interface MailerInterface
{
public function send(string $to, string $subject): bool;
}
class SmtpMailer implements MailerInterface
{
public function send(string $to, string $subject): bool
{
echo "SMTP queued email to {$to}: {$subject}" . PHP_EOL;
return true;
}
}
function sendWelcomeEmail(MailerInterface $mailer, string $email): void
{
$mailer->send($email, 'Welcome to KoderSolution');
}
sendWelcomeEmail(new SmtpMailer(), '[email protected]');
Notice how sendWelcomeEmail() type-hints MailerInterface instead of SmtpMailer. Tomorrow you can pass a SendGridMailer or InMemoryTestMailer without changing a single line inside sendWelcomeEmail().
public method signatures and constants.protected or private methods in an interface: Every method in an interface defines a public contract and must be public.Yes. An interface can extend one or more parent interfaces using extends, such as interface CacheableRepository extends RepositoryInterface.
Yes. Write extends first, followed by implements: class PdfReport extends BaseReport implements Exportable, Printable.
Create an interface when you expect multiple implementations (for example, Stripe vs PayPal, Redis vs File cache) or want clean mocking in tests.
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.