Introduction to Interfaces
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 27 of 91.
An interface defines a contract that classes must follow. Unlike abstract classes that can contain both abstract and concrete methods, an interface only declares method signatures without any implementation. Think of it as a promise: any class that implements an interface guarantees it will provide those specific methods.
You define an interface using the interface keyword:
<?php
interface Printable {
public function print();
}
This interface declares that any class implementing Printable must have a print() method. The interface doesn't care how the method works, only that it exists.
Here's a simple example showing the basic structure:
<?php
interface Drivable {
public function start();
public function stop();
}
Notice that interface methods have no body, just the signature ending with a semicolon. All methods in an interface are implicitly public, so you cannot use private or protected.
Interfaces are powerful because they allow unrelated classes to share common behavior. A Car and a Motorcycle might have nothing in common inheritance-wise, but both can implement Drivable to guarantee they have start() and stop() methods.
Key Point: An interface defines what methods a class must have, not how they should work. It establishes a contract that implementing classes must fulfill.
Challenge
EasyLet's build a simple messaging system that introduces you to interfaces. You'll define an interface that establishes a contract for how messages should be handled, setting the foundation for the implementing classes you'll create in the next lesson.
You'll organize your code across two files:
Messageable.php— Define an interface calledMessageablethat declares two method signatures:compose($content)for creating a message, anddeliver()for sending it. Remember, interface methods have no body — just the signature ending with a semicolon.main.php— Include the Messageable file. To verify your interface is correctly defined, use PHP'sinterface_exists()function to check ifMessageableexists. Then use theReflectionClassto inspect your interface and list its methods. Create a reflection of your interface, get its methods usinggetMethods(), and print each method name on its own line.
Your output should display the two method names that your interface declares, each on a separate line, in the order you defined them.
This challenge focuses purely on defining an interface — the contract that future classes will need to fulfill. You're establishing what methods must exist, without worrying about how they'll work. That implementation comes in the next lesson!
Cheat sheet
An interface defines a contract that classes must follow. It only declares method signatures without any implementation.
Define an interface using the interface keyword:
<?php
interface Printable {
public function print();
}
Interface methods have no body, just the signature ending with a semicolon. All methods in an interface are implicitly public.
<?php
interface Drivable {
public function start();
public function stop();
}
Interfaces allow unrelated classes to share common behavior by guaranteeing they implement specific methods.
Try it yourself
<?php
// Include the Messageable interface file
require_once 'Messageable.php';
// TODO: Use interface_exists() to check if Messageable interface exists
// TODO: Create a ReflectionClass object for the Messageable interface
// TODO: Get the methods using getMethods()
// TODO: Loop through the methods and print each method name on its own 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