0
0
PHPprogramming~3 mins

Why Abstract classes and methods in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could guarantee every part of your program follows the same rules without writing repetitive checks?

The Scenario

Imagine you are building a system for different types of vehicles. You want each vehicle to have a method to start the engine, but each vehicle starts differently. Writing separate code for each vehicle without a shared plan can get messy and confusing.

The Problem

Without a clear shared plan, you might forget to add the start method to some vehicles or write inconsistent code. This leads to bugs and makes your code hard to maintain or extend when new vehicle types are added.

The Solution

Abstract classes and methods let you create a blueprint for your vehicles. You define the start method as abstract, forcing every vehicle class to provide its own version. This keeps your code organized, consistent, and easier to manage.

Before vs After
Before
<?php
class Car {
  function start() {
    echo "Car engine starts";
  }
}
class Bike {
  // forgot to add start method
}
?>
After
<?php
abstract class Vehicle {
  abstract public function start();
}
class Car extends Vehicle {
  public function start() {
    echo "Car engine starts";
  }
}
class Bike extends Vehicle {
  public function start() {
    echo "Bike engine starts";
  }
}
?>
What It Enables

It enables you to enforce a consistent structure across related classes while allowing each to implement details their own way.

Real Life Example

Think of a remote control system where every device must have a power button. Abstract classes ensure every device class has a power method, but each device turns on differently.

Key Takeaways

Abstract classes provide a blueprint for related classes.

Abstract methods force subclasses to implement specific behaviors.

This approach keeps code consistent, organized, and easier to maintain.