R
Rishtaara
PHP Fundamentals
Lesson 22 of 32Article20 min

OOP — Abstract Classes, Interfaces & Traits

Abstract classes cannot be instantiated directly. They may contain abstract methods that child classes must implement.

Abstract Classes

Abstract classes cannot be instantiated directly. They may contain abstract methods that child classes must implement.

Real-life example: An abstract "Vehicle" says every vehicle must move(), but only Car and Bike fill in the details.

abstract class
<?php
abstract class Shape {
  abstract public function area(): float;

  public function describe(): string {
    return "Area: " . $this->area();
  }
}

class Circle extends Shape {
  public function __construct(private float $radius) {}

  public function area(): float {
    return pi() * $this->radius ** 2;
  }
}

$c = new Circle(5);
echo $c->describe();
?>

Interfaces

An interface lists method signatures without bodies. A class implements an interface with implements InterfaceName.

Real-life example: An interface is a job contract — "you must be able to sendEmail()" — any class hired must deliver.

interface example
<?php
interface Notifiable {
  public function notify(string $message): void;
}

class EmailNotifier implements Notifiable {
  public function notify(string $message): void {
    echo "Email sent: $message";
  }
}

$n = new EmailNotifier();
$n->notify("Welcome to Rishtaara!");
?>

Traits

Traits share methods across unrelated classes. Use trait Name inside a class body. Resolve conflicts with insteadof and as.

Real-life example: Traits are power-ups in a game — any character can equip "Loggable" without sharing a parent class.

trait example
<?php
trait Timestampable {
  public function touch(): void {
    echo "Updated at " . date("c");
  }
}

class Post {
  use Timestampable;
}

$post = new Post();
$post->touch();
?>