Lesson 15 of 20

Inheritance & Interfaces

Inheritance and Abstract Classes

PHP supports single inheritance with extends. Use abstract classes to define a template for subclasses.

Example
<?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 M_PI * $this->radius ** 2;
    }
}

class Rectangle extends Shape {
    public function __construct(
        private float $width,
        private float $height
    ) {}

    public function area(): float {
        return $this->width * $this->height;
    }
}

$shapes = [new Circle(5), new Rectangle(4, 6)];
foreach ($shapes as $shape) {
    echo $shape->describe() . "\n";
}
?>

Interfaces and Traits

Interfaces define contracts. Traits provide reusable methods that can be mixed into multiple classes.

Example
<?php
interface Loggable {
    public function log(): void;
}

interface Serializable {
    public function serialize(): string;
}

// Trait — reusable method bundles
trait TimestampTrait {
    private string $createdAt;

    public function setCreatedAt(): void {
        $this->createdAt = date('Y-m-d H:i:s');
    }

    public function getCreatedAt(): string {
        return $this->createdAt;
    }
}

class Post implements Loggable, Serializable {
    use TimestampTrait; // mix in the trait

    public function __construct(private string $title) {
        $this->setCreatedAt();
    }

    public function log(): void {
        echo "Post: {$this->title}\n";
    }

    public function serialize(): string {
        return json_encode(['title' => $this->title]);
    }
}
?>