Skip to main content

Course Progress

Loading...

Abstract Classes in PHP: Blueprint for Child Classes

Duration: 45 minutes
Module 2: Object-Oriented PHP

Learning Objectives

  • Understand OOP principles in PHP
  • Create and use classes and objects
  • Implement inheritance and polymorphism
  • Apply OOP best practices

Building a Foundation with Abstract Classes

Welcome to our exploration of abstract classes in PHP! Abstract classes are a fundamental concept in object-oriented programming that bridge the gap between interfaces and concrete classes. They provide a powerful way to establish common structures while enforcing implementation details in child classes.

Why Abstract Classes Matter: Abstract classes are essential for creating robust, maintainable PHP applications. In WordPress development, abstract classes form the backbone of many core components including widgets, admin pages, and REST API controllers. Understanding abstract classes will dramatically improve your ability to extend WordPress and create plugins that integrate seamlessly with core functionality.

Understanding Abstract Classes

Abstract classes are like architectural blueprints for a building. The blueprint itself isn't a building (you can't live in it), but it defines the essential structure that all actual buildings based on that blueprint must follow. Similarly, an abstract class can't be instantiated directly, but it defines a structure that all extending classes must adhere to.

Abstract Class Structure

Diagram
Class Diagram (Diagram converted to static representation) classDiagram class AbstractClass { > +regularMetho...

Key Characteristics of Abstract Classes

Cannot Be Instantiated

Abstract classes cannot be directly instantiated with the new keyword. They are meant to be extended by child classes.

###CODE_BLOCK_1###

Can Contain Abstract Methods

Abstract classes can declare abstract methods—methods without an implementation that must be defined by any non-abstract child class.

###CODE_BLOCK_2###

Can Contain Concrete Methods

Unlike interfaces, abstract classes can contain fully implemented (concrete) methods, providing common functionality to all child classes.

###CODE_BLOCK_3###

Can Contain Properties

Abstract classes can define properties (member variables) that child classes will inherit.

###CODE_BLOCK_4###

Can Declare Constructor Methods

Abstract classes can have constructor methods that child classes can call with parent::__construct().

###CODE_BLOCK_6###

The Restaurant Menu Analogy

Think of an abstract class as a restaurant franchise template:

  • The franchise headquarters creates a menu template (abstract class) with certain required dishes (abstract methods) that every franchise location must serve.
  • The template also includes standard recipes (concrete methods) that all locations will use exactly as specified.
  • You can't open a "template restaurant" (instantiate the abstract class), but you can open franchise locations (concrete child classes) that implement the required dishes while using the standard recipes.
  • Each location (child class) must provide its own implementation of the required dishes (abstract methods) based on local tastes and ingredients, but all locations share the same core identity and standards.

Abstract Class Syntax and Structure

Creating and working with abstract classes in PHP follows a specific syntax. Let's explore the structure of abstract classes and how to use them effectively.

Basic Abstract Class Syntax

###CODE_BLOCK_7###

Abstract Method Rules

  • Abstract methods can only exist within abstract classes or interfaces
  • Abstract methods cannot have an implementation (no method body)
  • Abstract methods end with a semicolon instead of curly braces
  • Abstract methods must specify access modifier (public, protected, or private)
  • When a child class implements an abstract method, it must maintain the same or a less restrictive visibility
  • The child implementation must match or have compatible parameter types and count

Extending an Abstract Class

###CODE_BLOCK_8###

Multiple Levels of Inheritance with Abstract Classes

Abstract classes can extend other abstract classes, creating a chain of inheritance where each level can add its own abstract and concrete methods.

Multi-level Abstract Inheritance

Diagram
Class Diagram (Diagram converted to static representation) classDiagram class BaseAbstract { > +baseMethod() ...

Multi-level Abstract Class Example

###CODE_BLOCK_9###

Abstract Classes vs. Interfaces

One of the most common questions in OOP is when to use an abstract class versus an interface. Both provide a way to define a contract that implementers must follow, but they have important differences.

Comparing Abstract Classes and Interfaces

Feature Abstract Class Interface
Instantiation Cannot be instantiated Cannot be instantiated
Method implementation Can contain both concrete and abstract methods Can only contain method signatures (PHP 8.0+ allows default method implementations)
Properties Can contain properties with any visibility Can only contain public constants (no variables)
Constructor Can have a constructor Cannot have a constructor
Inheritance Single inheritance only (can extend one class) Multiple inheritance (can implement many interfaces)
Access modifiers Can use public, protected, and private All methods are implicitly public
Use case "Is-a" relationship with shared implementation "Can-do" relationship (capability contract)

Abstract Class vs. Interface Example

###CODE_BLOCK_10###

When to Use Abstract Classes vs. Interfaces

Use Abstract Classes When:

  • You want to share code among related classes (common implementation)
  • The classes that extend your abstract class have many common methods or fields
  • You need to declare non-public members (protected/private methods or properties)
  • You need constructor logic in the base type
  • You're building a framework with base functionality that will be customized
  • You have an "is-a" relationship that shares behavior

Use Interfaces When:

  • You expect unrelated classes to implement your interface
  • You want to specify a behavior but not its implementation
  • You need multiple inheritance (a class can implement multiple interfaces)
  • You're defining a contract for a plugin system or API
  • You have a "can-do" relationship (capability) rather than an "is-a" relationship

Best of Both Worlds: Using Interfaces and Abstract Classes Together

Many robust designs use both abstract classes and interfaces together. An abstract class can implement interfaces, providing a partial implementation for its child classes.

###CODE_BLOCK_11###

Abstract Classes in the Real World

Example 1: WordPress Widget Framework

WordPress uses an abstract class for its widget framework. The WP_Widget abstract class provides base functionality for all widget types while requiring specific implementations for widget rendering and form handling.

WordPress Widget Abstract Class (Simplified)

###CODE_BLOCK_13###

Example 2: Database Abstraction Layer

Database abstraction layers often use abstract classes to provide a common interface for different database systems while allowing system-specific implementations.

Database Abstraction Layer Example

###CODE_BLOCK_14###

Example 3: Template Method Design Pattern

The Template Method pattern is a common use case for abstract classes. It defines the skeleton of an algorithm but allows subclasses to override specific steps.

Report Generator Example

###CODE_BLOCK_15###

Abstract Classes in WordPress Development

WordPress core and many popular plugins make extensive use of abstract classes. Understanding these patterns will help you create more professional WordPress extensions.

WordPress REST API Controllers

The WordPress REST API uses abstract classes to define the structure of controller classes for different resources.

WordPress REST Controller Example

###CODE_BLOCK_16###

The WordPress Admin Settings API

Creating an abstract class for admin pages can help standardize your plugin's admin interface while allowing for customization.

Custom Admin Page Abstract Class

###CODE_BLOCK_17###

Best Practices for Abstract Classes

Keep the Abstract Interface Minimal

Only make methods abstract when they absolutely must be implemented differently in child classes. If a method has a sensible default implementation, make it concrete with the option to override.

###CODE_BLOCK_18###

Use Template Method Pattern

The Template Method pattern is a natural fit for abstract classes. Define the skeleton of an algorithm in the parent class, deferring some steps to subclasses.

###CODE_BLOCK_19###

Provide Constructors for Common Initialization

Use constructors in abstract classes to handle common initialization code that all child classes need.

###CODE_BLOCK_20###

Use Class Constants for Configuration

Abstract classes can define constants that child classes can use for configuration without overriding.

###CODE_BLOCK_21###

Document Abstract Methods Thoroughly

Abstract methods should have thorough PHPDoc comments to guide implementers on what the method should do and return.

###CODE_BLOCK_22###

Use Protected Instead of Private for Extensibility

Use protected visibility for properties and methods that child classes may need to access or override. Private members aren't available to child classes.

###CODE_BLOCK_23###

Homework: Extend Your Previous Class with Abstract Classes

Assignment: Building a Product Framework with Abstract Classes

For this assignment, you'll refactor the Product class hierarchy from the previous homework to use abstract classes. You'll create an abstract base class that defines the common structure and behavior for different types of products.

Requirements:

  1. Create an abstract AbstractProduct class with:
    • Protected properties for name, price, and SKU
    • A constructor that sets these properties
    • Getters and setters for each property
    • At least one concrete method that provides common functionality
    • At least one abstract method that child classes must implement
  2. Create at least two concrete product classes (e.g., PhysicalProduct and DigitalProduct) that extend the abstract class
  3. Implement all required abstract methods in each child class
  4. Add at least one unique method to each child class that makes sense for its type
  5. Create a test script that demonstrates the functionality of your classes

Starter Code:

###CODE_BLOCK_27###

Bonus Challenges:

  • Create a third product type (e.g., SubscriptionProduct) with unique properties and behavior
  • Add an abstract save() method that each product implements differently (e.g., saving to database, file, etc.)
  • Create a ProductFactory class that can create different product types based on input
  • Implement the Template Method pattern in the abstract class for a complex operation like "process order"

Key Takeaways

Purpose of Abstract Classes

Abstract classes provide a way to define a common structure and behavior for related classes while requiring specific implementations for certain methods.

Abstract vs. Concrete Methods

Abstract classes can contain both abstract methods (without implementation) and concrete methods (with implementation), allowing for shared code and required customization.

Class Hierarchy

Abstract classes are ideal for creating class hierarchies where child classes share common properties and methods but need to implement specific behaviors differently.

Abstract vs. Interface

Use abstract classes when you have an "is-a" relationship with shared implementation. Use interfaces when you have a "can-do" relationship or need multiple inheritance.

Template Method Pattern

Abstract classes are perfect for implementing the Template Method pattern, which defines the skeleton of an algorithm but allows subclasses to override specific steps.

Next Steps

Now that you understand abstract classes, we'll continue exploring advanced OOP concepts with interfaces, which provide another way to define contracts between classes. Together, abstract classes and interfaces give you powerful tools for creating flexible, maintainable PHP applications and WordPress extensions.

Additional Resources