Multiple Interface Implement
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 29 of 91.
Unlike inheritance where a class can only extend one parent, PHP allows a class to implement multiple interfaces. This gives you the flexibility to combine different contracts, making your classes more versatile.
To implement multiple interfaces, separate them with commas after the implements keyword:
<?php
interface Printable {
public function print();
}
interface Savable {
public function save();
}
class Report implements Printable, Savable {
private $title;
public function __construct($title) {
$this->title = $title;
}
public function print() {
return "Printing: " . $this->title;
}
public function save() {
return "Saving: " . $this->title;
}
}
$report = new Report("Sales Report");
echo $report->print() . "\n";
echo $report->save();
Output:
Printing: Sales Report
Saving: Sales ReportThe Report class fulfills both contracts by implementing all methods from Printable and Savable. You must provide implementations for every method declared in each interface.
This approach is powerful because it lets you build classes that satisfy multiple requirements without the constraints of single inheritance. A class can be printable, savable, exportable, and more, all at once.
Key Point: Use commas to implement multiple interfaces. Your class must provide concrete implementations for all methods from every interface it implements.
Challenge
EasyLet's build a media file system that demonstrates how a single class can implement multiple interfaces to gain different capabilities.
You'll create four files that work together to handle media files that can be both played and shared:
Playable.php— Define aPlayableinterface with a single method signature:play(). This contract ensures any playable media can be started.Shareable.php— Define aShareableinterface with a single method signature:share($platform). This contract ensures any shareable content can be distributed to different platforms.Video.php— Create aVideoclass that implements bothPlayableandShareable. Include both interface files at the top. The class should have a private$titleproperty and a private$durationproperty (in minutes). The constructor accepts the title and duration. Implementplay()to return"Playing video: [title] ([duration] min)". Implementshare($platform)to return"Sharing [title] on [platform]".main.php— Include the Video file. You'll receive three inputs: the video title, duration (as a string to convert to an integer), and a platform name. Create aVideoobject with the title and duration. Print the result of callingplay()on the first line, then print the result of callingshare()with the platform on the second line.
Your Video class fulfills two separate contracts simultaneously — it can be played like any media, and it can be shared to social platforms. This is the power of implementing multiple interfaces: a single class gains capabilities from different sources without being limited to a single inheritance chain.
Cheat sheet
A class can implement multiple interfaces by separating them with commas after the implements keyword:
<?php
interface Printable {
public function print();
}
interface Savable {
public function save();
}
class Report implements Printable, Savable {
public function print() {
return "Printing report";
}
public function save() {
return "Saving report";
}
}The class must provide concrete implementations for all methods from every interface it implements. This allows a class to fulfill multiple contracts simultaneously without the constraints of single inheritance.
Try it yourself
<?php
// Include the Video file
require_once 'Video.php';
// Read inputs
$title = trim(fgets(STDIN));
$duration = intval(trim(fgets(STDIN)));
$platform = trim(fgets(STDIN));
// TODO: Create a Video object with the title and duration
// TODO: Print the result of calling play() on the first line
// TODO: Print the result of calling share() with the platform on the second line
?>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