PHP Inheritance

A class can extend another, inheriting its properties and methods.

PHP
<?php
class Product
{
    public function __construct(
        public string $name,
        public float  $price,
    ) {}

    public function describe(): string
    {
        return "{$this->name} — NPR {$this->price}";
    }
}

class Book extends Product
{
    public function __construct(
        string $name,
        float $price,
        public string $author,
    ) {
        parent::__construct($name, $price);
    }

    public function describe(): string
    {
        return parent::describe() . " by {$this->author}";
    }
}

$b = new Book("Palpasa Cafe", 480, "Narayan Wagle");
echo $b->describe(); // Palpasa Cafe — NPR 480 by Narayan Wagle

parent:: calls the parent version — essential in a constructor, and useful when you want to extend rather than replace behaviour.

Abstract classes

An abstract class cannot be instantiated; it exists to be extended, and can force subclasses to implement certain methods.

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

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

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

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

echo (new Circle(3))->describe();

Forgetting to implement area() in a subclass is a fatal error at compile time — exactly when you want to find out.

final

final stops further extension or overriding:

PHP
<?php
final class Config { }          // cannot be extended

class Base {
    final public function id(): string { return 'x'; }  // cannot be overridden
}

Checking types

PHP
<?php
  var_dump($b instanceof Book);     // true
  var_dump($b instanceof Product);  // true — inheritance counts
  echo get_class($b);                // Book