← Back to Chapters

PHP OOP Abstract Class

? PHP OOP Abstract Class

? Quick Overview

An abstract class in PHP provides a blueprint for other classes. It defines common methods and forces child classes to implement required behavior.

? Key Concepts

  • Abstract classes cannot be instantiated
  • Contain abstract and normal methods
  • Used to enforce structure across subclasses

? Syntax / Theory

Abstract classes are declared using the abstract keyword. Any method declared abstract must be implemented by child classes.

? Code Example

? View Code Example
// Abstract class defining common behavior
abstract class Animal {
// Abstract method to be implemented by child classes
public abstract function makeSound();
// Concrete method shared by all animals
public function sleep() {
echo "Sleeping...";
}
}
// Dog class extending abstract Animal
class Dog extends Animal {
public function makeSound() {
echo "Bark!";
}
}
// Creating object of child class
$dog = new Dog();
$dog->makeSound();
$dog->sleep();

? Live Output / Explanation

The Dog class implements the abstract method makeSound(). The object can call both abstract and concrete methods.

? Interactive Concept

Think of an abstract class as a contract. Every child class must agree to implement required methods before it can be used.

? Use Cases

  • Framework base classes
  • Defining templates for modules
  • Ensuring consistent method structure

? Tips & Best Practices

  • Use abstract classes when behavior is shared
  • Keep abstract methods meaningful
  • Prefer abstract classes over interfaces when logic is shared

? Try It Yourself

  • Create an abstract Vehicle class
  • Add startEngine() abstract method
  • Implement it in Car and Bike