HomePHP OOPSAbstraction in PHP

Abstraction in PHP

Abstraction in PHP

Abstraction in PHP means showing only the necessary details to the user and hiding the internal implementation.
It focuses on what an object does instead of how it does it.

In PHP, abstraction is implemented using abstract classes and interfaces.


1. Abstract Class

  • An abstract class is a class that cannot be instantiated directly.
  • It can have abstract methods (without body) and normal methods (with body).
  • A child class must implement all abstract methods.

Example:

<?php
abstract class Shape {
    // Abstract method (must be implemented in child class)
    abstract public function area();

    // Normal method (optional to override)
    public function display() {
        echo "Calculating Shape Area...\n";
    }
}

class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    // Implementing abstract method
    public function area() {
        return pi() * pow($this->radius, 2);
    }
}

// $shape = new Shape(); ❌ Error: Cannot instantiate abstract class
$circle = new Circle(5);
$circle->display();
echo "Area of Circle: " . $circle->area();

2. Interface

  • An interface is like a contract — it only contains method declarations (no body).
  • A class implementing an interface must define all methods from the interface.
  • A class can implement multiple interfaces (supports multiple inheritance).

Example:

<?php
interface Logger {
    public function log($message);
}

interface Notifier {
    public function sendNotification($message);
}

class AppLogger implements Logger, Notifier {
    public function log($message) {
        echo "Log: $message\n";
    }
    public function sendNotification($message) {
        echo "Notification: $message\n";
    }
}

$app = new AppLogger();
$app->log("User logged in");
$app->sendNotification("Welcome, User!");

Key Differences Between Abstract Class & Interface

FeatureAbstract ClassInterface
MethodsCan have both abstract & normal methodsOnly method declarations
PropertiesCan have propertiesCannot have properties (constants allowed)
Multiple InheritanceNoYes
PurposeFor closely related classesFor unrelated classes but with common methods

Real-life Example:
Think of a “TV Remote” – you know what buttons to press (methods), but you don’t know (or need to know) how the TV processes those signals internally.
That’s abstraction — focus on what, hide the how.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *