PHP - Inheritance

Inheritance is a core concept in object-oriented programming (OOP) that allows you to create a new class (subclass or derived class) based on an existing class (superclass or base class). The derived class inherits the properties and methods of the base class, and you can extend or override its behavior. In advanced PHP programming, inheritance provides a way to create a hierarchy of classes that share common attributes and behaviors. Here's how inheritance works in PHP:

Base Class (Superclass):

The base class serves as the foundation for the derived classes. It contains properties, methods, and behaviors that are shared by multiple derived classes.

class Animal {

    public $name;    

    public function speak() {

        return "Some sound";

    }

}

Derived Class (Subclass):

A derived class inherits properties and methods from the base class. You can extend the behavior of the base class by adding new properties or methods, and you can also override existing methods.

class Dog extends Animal {

    public function speak() {

        return "Woof!";

    }

}

class Cat extends Animal {

    public function speak() {

        return "Meow!";

    }

}

In the example above, both Dog and Cat are derived classes that inherit the name property and speak() method from the Animal base class. However, they override the speak() method to provide their own unique behavior.

Accessing Base Class Members:

Derived classes can access the properties and methods of the base class using the parent keyword.

class Dog extends Animal {

    public function speak() {

        return parent::speak() . " Woof!";

    }

}

In this example, the speak() method in the Dog class first calls the speak() method of the parent class using parent::speak() and then appends " Woof!".

Constructor Inheritance:

The base class's constructor is not automatically called when creating an instance of the derived class. To ensure the base class's constructor is executed, you can use the parent::__construct() method inside the derived class's constructor.

The instanceof Operator:

You can use the instanceof operator to check if an object belongs to a specific class or its subclasses.

$dog = new Dog();

if ($dog instanceof Animal) {

    echo "The dog is an animal.";

}

Inheritance allows you to create a hierarchy of classes that share common functionality while allowing for specialization and customization. It promotes code reuse and modular design, making your code more organized and maintainable.