← Back to Chapters

PHP OOP Inheritance

? PHP OOP Inheritance

? Quick Overview

Inheritance in PHP allows a class to acquire the properties and methods of another class. It is a core concept of Object-Oriented Programming that promotes reuse and clean design.

? Key Concepts

  • Parent class defines common behavior
  • Child class reuses and customizes parent logic
  • Achieved using the extends keyword

? Syntax & Theory

A child class inherits all public and protected members of the parent class. Methods can be overridden to provide specific behavior.

? View Code Example
// Parent class definition
<?php
class Animal {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function makeSound() {
        return "Some generic sound";
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    public function makeSound() {
        return "Woof! Woof!";
    }
}

$dog = new Dog("Buddy");
echo $dog->name . " says " . $dog->makeSound();
?>

?️ Live Output / Explanation

The Dog class inherits the name property from Animal and overrides the makeSound() method to provide a specific sound.

? Example with Methods

? View Code Example
// Base class for vehicles
<?php
class Vehicle {
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function intro() {
        return "This is a vehicle of brand: " . $this->brand;
    }
}

// Car class extending Vehicle
class Car extends Vehicle {
    public function message() {
        return "This is a car, brand: " . $this->brand;
    }
}

$car = new Car("Toyota");
echo $car->intro();
echo "<br>";
echo $car->message();
?>

? Interactive Concept Flow

Animal → Dog
Vehicle → Car
Child classes automatically gain access to parent functionality and can customize it.

? Use Cases

  • Building base models for applications
  • Reducing duplicate code
  • Implementing polymorphism

? Tips & Best Practices

  • Use parent::methodName() to call parent logic
  • Keep parent classes generic
  • Prefer composition when inheritance is not logical

? Try It Yourself

  • Create a Shape class with an area() method
  • Extend it using a Rectangle class
  • Override the area() method and print the result
? View Code Example
// Simple PHP inheritance output test
<?php
echo "Hello from 10.3 PHP OOP Inheritance";
?>