PHP OOP Inheritance

In PHP Object-Oriented Programming (OOP), inheritance allows a class (child or subclass) to inherit properties and methods from another class (parent or superclass). This enables code reusability and hierarchical relationships between classes.

Example of Inheritance in PHP:





<?php
// Parent class
class Vehicle {
    public $brand;
    public $model;

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

    public function startEngine() {
        return "The engine of $this->brand $this->model is starting.";
    }
}

// Child class inheriting from Vehicle
class Car extends Vehicle {
    public $topSpeed;

    public function __construct($brand, $model, $topSpeed) {
        parent::__construct($brand, $model); // Call parent constructor
        $this->topSpeed = $topSpeed;
    }

    public function showDetails() {
        return "$this->brand $this->model has a top speed of $this->topSpeed km/h.";
    }
}

// Using the Car class
$myCar = new Car('Toyota', 'Supra', 250);
echo $myCar->startEngine();  // Inherited method
echo "\n";
echo $myCar->showDetails();  // Method in child class
?>

Key Concepts:

  1. Parent Class (Vehicle): The base class from which the child class inherits.
  2. Child Class (Car): The class that inherits from the parent class.
  3. parent::__construct(): The child class can call the parent class’s constructor using the parent keyword.
  4. Inheritance of Methods and Properties: The child class inherits all non-private properties and methods from the parent class.

Use Cases:

  • Code Reusability: Common functionality can be defined in the parent class and reused in child classes.
  • Hierarchy: Define generic behaviors in parent classes and specific behaviors in child classes.

Leave a Reply

Your email address will not be published. Required fields are marked *