Abstract Classes
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 25 of 91.
An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes, defining methods that child classes must implement. You create an abstract class using the abstract keyword.
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function calculateArea();
public function getColor() {
return $this->color;
}
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}
$rect = new Rectangle("blue", 5, 3);
echo $rect->calculateArea();
Output:
15The Shape class declares an abstract method calculateArea() without providing an implementation. Any class extending Shape must implement this method. Notice that abstract classes can also contain regular methods like getColor() that child classes inherit directly.
Abstract methods define what a child class must do, but not how. This ensures all shapes have a calculateArea() method while letting each shape calculate its area differently.
Key Point: Abstract classes combine the structure of inheritance with enforced requirements. Use them when you want to share code among related classes while ensuring certain methods are implemented by each child class.
Challenge
EasyLet's build a media player system that demonstrates how abstract classes enforce a contract while allowing different media types to implement their own playback behavior.
You'll organize your code across three files:
Media.php— Define an abstractMediaclass that serves as the blueprint for all media types. It should have a protected$titleproperty and a constructor that accepts and sets the title. Include an abstract method calledplay()that child classes must implement. Also add a regular methodgetTitle()that returns the title — this concrete method will be inherited by all child classes.Song.php— Define aSongclass that extendsMedia. Include the Media file at the top. This class adds an$artistproperty. The constructor should accept title and artist — useparent::__construct()for the title, then set the artist yourself. Implement the requiredplay()method to return"Playing song: [title] by [artist]".Podcast.php— Define aPodcastclass that extendsMedia. Include the Media file at the top. This class adds an$episodeproperty (an integer). The constructor should accept title and episode number — useparent::__construct()for the title, then set the episode. Implement the requiredplay()method to return"Playing podcast: [title] - Episode [episode]".
In main.php, include both the Song and Podcast files. You'll receive four inputs: the song title, artist name, podcast title, and episode number (as a string to convert to an integer). Create a Song and a Podcast object with these values. Print the result of calling play() on the song first, then on the podcast, each on its own line.
This challenge shows how abstract classes define a contract — every media type must have a play() method, but each type implements it differently. The abstract Media class cannot be instantiated directly; it only exists to provide structure and shared functionality to its children.
Cheat sheet
An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes, defining methods that child classes must implement. Use the abstract keyword to create an abstract class.
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function calculateArea();
public function getColor() {
return $this->color;
}
}Child classes must implement all abstract methods:
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}Key characteristics:
- Abstract classes cannot be instantiated directly
- Abstract methods have no implementation in the abstract class
- Child classes must implement all abstract methods
- Abstract classes can contain both abstract and regular methods
- Regular methods in abstract classes are inherited by child classes
Try it yourself
<?php
require_once 'Song.php';
require_once 'Podcast.php';
// Read inputs
$songTitle = trim(fgets(STDIN));
$artistName = trim(fgets(STDIN));
$podcastTitle = trim(fgets(STDIN));
$episodeNumber = intval(trim(fgets(STDIN)));
// TODO: Create a Song object with songTitle and artistName
// TODO: Create a Podcast object with podcastTitle and episodeNumber
// TODO: Print the result of calling play() on the song
// TODO: Print the result of calling play() on the podcast
?>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