Topics Object-Oriented PHP Inheritance & Polymorphism
intermediate 15 min read

Inheritance & Polymorphism

Extending classes, overriding methods, parent calls, final keyword, and LSP.

Inheritance

class Animal {
public function __construct(
protected string \$name
) { }
public function speak(): string {
return "\$this->name makes a sound";
}
}

class Dog extends Animal {
public function speak(): string {
return "\$this->name barks";
}
}

Parent Constructor

class Puppy extends Dog {
public function __construct(string \$name, private int \$age) {
parent::__construct(\$name);
}
}

Final Keyword

final class cannot be extended. final method cannot be overridden.

Polymorphism

Objects of different classes can be used interchangeably if they share a parent class or interface.

Examples

<?php
class Shape {
    public function area(): float { return 0; }
}
class Circle extends Shape {
    public function __construct(private float $radius) {}
    public function area(): float { return pi() * $this->radius ** 2; }
}
class Square extends Shape {
    public function __construct(private float $side) {}
    public function area(): float { return $this->side ** 2; }
}
$shapes = [new Circle(5), new Square(4)];
foreach ($shapes as $s) echo get_class($s) . ': ' . $s->area() . "\n";

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.