PHP OOP - Inheritance

In PHP, inheritance is a fundamental concept of object-oriented programming (OOP) that allows a class (called the subclass or derived class) to inherit properties and methods from another class (called the superclass or base class). Inheritance promotes code reusability and allows you to create a hierarchy of classes, where subclasses inherit the characteristics of their parent classes and can extend or override their functionality.


To establish inheritance in PHP, you use the `extends` keyword. Here's the basic syntax for creating a subclass that inherits from a superclass:

php
class Superclass {
    // Superclass properties and methods
}

class Subclass extends Superclass {
    // Subclass properties and methods
}

The `Subclass` in the above example is inheriting from `Superclass`. As a result, the `Subclass` automatically gains access to all the public and protected properties and methods defined in the `Superclass`. Private properties and methods, however, are not inherited and remain accessible only within the class where they are defined.


Let's illustrate this with a practical example:

php
class Animal {
    protected $species;

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

    public function makeSound() {
        return 'Animal sound';
    }
}

class Dog extends Animal {
    public function makeSound() {
        return 'Woof! Woof!';
    }
}

class Cat extends Animal {
    public function makeSound() {
        return 'Meow!';
    }
}

// Creating objects of subclasses
$dog = new Dog('Canine');
$cat = new Cat('Feline');

// Calling methods on objects
echo $dog->makeSound(); // Output: Woof! Woof!
echo $cat->makeSound(); // Output: Meow!

In this example, we have a superclass `Animal`, which has a property `$species` and a method `makeSound()`. We then have two subclasses `Dog` and `Cat`, which inherit from the `Animal` class. The `Dog` and `Cat` classes override the `makeSound()` method, providing their specific implementation of the sound.


Inheritance allows you to create a hierarchy of related classes, providing a way to organize and reuse code effectively. It is a powerful mechanism in OOP that enables you to model real-world relationships and build complex systems with shared characteristics and specialized behaviors.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext