PHP OOP Inheritance & Interfaces

extends, abstract classes, interfaces and traits.

✍️ 2 exercises in this lesson
  • class Child extends ParentClass: inherit members; call the parent with parent::method().
  • abstract class: cannot be instantiated; can declare abstract methods children must implement.
  • interface: a contract of methods a class promises to implement (implements).
  • trait: reusable methods you can use inside several classes.
  • final: prevents overriding or extending.

Key Takeaways: PHP OOP Inheritance & Interfaces

Mastering PHP OOP Inheritance & Interfaces helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP OOP Inheritance & Interfaces Code Example

PHP
<?php
interface Shape { public function area(): float; }

trait Describes {
    public function describe(): string {
        return static::class . " with area " . round($this->area(), 2);
    }
}

abstract class BaseShape implements Shape { use Describes; }

class Circle extends BaseShape {
    public function __construct(private float $r) {}
    public function area(): float { return M_PI * $this->r ** 2; }
}

class Rectangle extends BaseShape {
    public function __construct(private float $w, private float $h) {}
    public function area(): float { return $this->w * $this->h; }
}

foreach ([new Circle(2), new Rectangle(3, 4)] as $shape) {
    echo $shape->describe() . "<br>";
}
Output
Circle with area 12.57
Rectangle with area 12
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP OOP Inheritance & Interfaces Practice Exercises

Check what you learned in “PHP OOP Inheritance & Interfaces”.

/ 2 solved
Fill in the blank

Make Dog inherit from Animal.

class Dog  Animal { }
✓ Correct! Not quite. Try again.
Multiple choice

Which keyword reuses methods from a trait?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services