PHP OOP – Inheritance

Welcome to The Coding College! In this tutorial, we’ll explore inheritance in PHP, one of the key principles of Object-Oriented Programming (OOP). Inheritance enables you to create new classes based on existing ones, promoting code reuse and modularity.

What is Inheritance?

In PHP, inheritance allows a class (called the child or derived class) to inherit properties and methods from another class (called the parent or base class).

  • The child class can use or override the properties and methods of the parent class.
  • This helps in reducing code duplication and creating a hierarchy of classes.

Syntax of Inheritance

In PHP, a class can inherit another class using the extends keyword.

<?php
class ParentClass {
    // Parent class code
}

class ChildClass extends ParentClass {
    // Child class code
}
?>

Example: Basic Inheritance

Let’s look at a simple example:

<?php
class Vehicle {
    public $brand;

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

    public function getBrand() {
        return $this->brand;
    }
}

class Car extends Vehicle {
    public $model;

    public function setModel($model) {
        $this->model = $model;
    }

    public function getModel() {
        return $this->model;
    }
}

// Create an object of the child class
$car = new Car();
$car->setBrand("Toyota");
$car->setModel("Corolla");

echo "Brand: " . $car->getBrand() . "<br>"; // Output: Brand: Toyota
echo "Model: " . $car->getModel();          // Output: Model: Corolla
?>

Explanation:

  1. The Car class inherits the properties and methods of the Vehicle class.
  2. The Car class can use both its own methods (setModel and getModel) and the inherited methods (setBrand and getBrand).

Overriding Methods in Inheritance

A child class can override a method from the parent class by redefining it.

Example: Overriding a Method

<?php
class Animal {
    public function makeSound() {
        echo "The animal makes a sound.<br>";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "The dog barks.<br>";
    }
}

$animal = new Animal();
$animal->makeSound(); // Output: The animal makes a sound.

$dog = new Dog();
$dog->makeSound();    // Output: The dog barks.
?>

Key Point:

To call the parent class’s version of a method from the child class, you can use the parent:: keyword:

<?php
class Dog extends Animal {
    public function makeSound() {
        parent::makeSound(); // Call parent method
        echo "The dog barks.<br>";
    }
}

$dog = new Dog();
$dog->makeSound();
// Output:
// The animal makes a sound.
// The dog barks.
?>

Access Modifiers and Inheritance

Access modifiers determine what is inherited and how it can be accessed:

  • Public properties and methods are fully inherited and accessible everywhere.
  • Protected properties and methods are inherited but can only be accessed within the class or its child classes.
  • Private properties and methods are not inherited and can only be accessed within the parent class.

Example: Access Modifiers with Inheritance

<?php
class ParentClass {
    public $publicVar = "Public";
    protected $protectedVar = "Protected";
    private $privateVar = "Private";

    public function showVars() {
        echo "Parent: $this->publicVar, $this->protectedVar, $this->privateVar<br>";
    }
}

class ChildClass extends ParentClass {
    public function showInheritedVars() {
        echo "Child: $this->publicVar, $this->protectedVar<br>";
        // Cannot access $this->privateVar here
    }
}

$parent = new ParentClass();
$parent->showVars(); // Output: Parent: Public, Protected, Private

$child = new ChildClass();
$child->showInheritedVars(); // Output: Child: Public, Protected
// Direct access to $child->privateVar will cause an error.
?>

final Keyword

The final keyword can be used in PHP to prevent a class or a method from being overridden or inherited.

Example: Using final

  1. Final Class: A class marked as final cannot be extended by any child class.
<?php
final class FinalClass {
    public function sayHello() {
        echo "Hello from the final class.<br>";
    }
}

// This will cause an error:
// class ChildClass extends FinalClass {}
?>
  1. Final Method: A method marked as final cannot be overridden in child classes.
<?php
class ParentClass {
    final public function sayHello() {
        echo "Hello from the final method.<br>";
    }
}

class ChildClass extends ParentClass {
    // This will cause an error:
    // public function sayHello() {}
}
?>

Real-World Example: Inheritance in Action

Let’s consider a real-world scenario where inheritance is used in an e-commerce system.

<?php
class Product {
    protected $name;
    protected $price;

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

    public function getDetails() {
        return "Product: $this->name, Price: $$this->price";
    }
}

class Electronic extends Product {
    private $warranty;

    public function __construct($name, $price, $warranty) {
        parent::__construct($name, $price); // Call the parent constructor
        $this->warranty = $warranty;
    }

    public function getDetails() {
        return parent::getDetails() . ", Warranty: $this->warranty years";
    }
}

$tv = new Electronic("Smart TV", 1200, 2);
echo $tv->getDetails();
// Output: Product: Smart TV, Price: $1200, Warranty: 2 years
?>

Key Points About Inheritance

  1. Single Inheritance: PHP only supports single inheritance (a class can extend only one parent class).
  2. Reusability: Allows you to reuse and extend functionality of an existing class.
  3. Method Overriding: Child classes can redefine methods to provide their own implementation.
  4. Parent Constructor: Use parent::__construct() to invoke the parent class’s constructor when extending.

Advantages of Inheritance

  1. Code Reusability: Reduces duplication by reusing existing functionality.
  2. Modularity: Makes it easier to structure and organize your code.
  3. Scalability: Simplifies the process of extending functionality for future needs.

Conclusion

Inheritance is one of the core features of PHP OOP that allows you to build on existing code, promoting reuse and reducing redundancy. By understanding and applying inheritance effectively, you can create modular, scalable, and efficient applications.

For more hands-on PHP tutorials and practical coding tips, visit The Coding College.

Leave a Comment