Implementing Interfaces
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 28 of 91.
Now that you understand what interfaces are, let's see how to actually implement them. A class implements an interface using the implements keyword, and must provide concrete implementations for all methods declared in that interface.
<?php
interface Printable {
public function print();
}
class Document implements Printable {
private $content;
public function __construct($content) {
$this->content = $content;
}
public function print() {
return "Printing: " . $this->content;
}
}
$doc = new Document("Hello World");
echo $doc->print();
Output:
Printing: Hello WorldThe Document class implements Printable by providing its own version of the print() method. If you forget to implement a required method, PHP will throw a fatal error.
Different classes can implement the same interface in their own way:
<?php
class Invoice implements Printable {
private $amount;
public function __construct($amount) {
$this->amount = $amount;
}
public function print() {
return "Invoice Total: $" . $this->amount;
}
}
$invoice = new Invoice(150);
echo $invoice->print();
Output:
Invoice Total: $150Both Document and Invoice fulfill the Printable contract, but each handles printing differently based on its purpose.
Key Point: Use implements to connect a class to an interface, then define all required methods. Each implementing class provides its own logic while guaranteeing the same method signatures exist.
Challenge
EasyLet's build a messaging system that demonstrates how different classes can implement the same interface in their own unique ways.
You'll create three files that work together to handle different types of messages:
Messageable.php— Define theMessageableinterface with two method signatures:compose($content)anddeliver(). This interface establishes the contract that all message types must follow.Email.php— Create anEmailclass that implementsMessageable. Include the interface file at the top. The class should have a private$recipientproperty and a private$bodyproperty. The constructor accepts the recipient address. Implementcompose($content)to store the content in$bodyand return"Email composed". Implementdeliver()to return"Email to [recipient]: [body]".SMS.php— Create anSMSclass that also implementsMessageable. Include the interface file at the top. The class should have a private$phoneNumberproperty and a private$textproperty. The constructor accepts the phone number. Implementcompose($content)to store the content in$textand return"SMS composed". Implementdeliver()to return"SMS to [phoneNumber]: [text]".
In main.php, include both the Email and SMS files. You'll receive three inputs: an email address, a phone number, and a message content. Create an Email object with the email address and an SMS object with the phone number. Call compose() with the message content on both objects, printing each result on its own line. Then call deliver() on both objects, printing each result on its own line. The order should be: email compose, SMS compose, email deliver, SMS deliver.
Both classes fulfill the same Messageable contract, but each handles composing and delivering messages according to its own purpose — emails show the recipient address while SMS messages show the phone number.
Cheat sheet
A class implements an interface using the implements keyword and must provide concrete implementations for all methods declared in that interface:
<?php
interface Printable {
public function print();
}
class Document implements Printable {
private $content;
public function __construct($content) {
$this->content = $content;
}
public function print() {
return "Printing: " . $this->content;
}
}
Multiple classes can implement the same interface, each providing their own implementation:
<?php
class Invoice implements Printable {
private $amount;
public function __construct($amount) {
$this->amount = $amount;
}
public function print() {
return "Invoice Total: $" . $this->amount;
}
}
If a class fails to implement all required methods from an interface, PHP will throw a fatal error.
Try it yourself
<?php
require_once 'Email.php';
require_once 'SMS.php';
// Read inputs
$emailAddress = trim(fgets(STDIN));
$phoneNumber = trim(fgets(STDIN));
$messageContent = trim(fgets(STDIN));
// TODO: Create an Email object with the email address
// TODO: Create an SMS object with the phone number
// TODO: Call compose() on both objects and print results
// Order: email compose, then SMS compose
// TODO: Call deliver() on both objects and print results
// Order: email deliver, then SMS deliver
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern