PHP Inheritance OOP

Inheritance is an important concept in object-oriented programming (OOP) that allows you to create new classes based on existing classes.

In PHP, you can implement inheritance using the extends keyword.

The class that is being inherited from is called the parent class or base class, and the class that inherits from it is called the child class or derived class.

Here’s an example of how inheritance works in PHP:

class Animal {
    protected $name;

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

    public function eat() {
        echo $this->name . " is eating.";
    }
}

class Dog extends Animal {
    public function bark() {
        echo $this->name . " is barking.";
    }
}

// Creating an instance of the Animal class
$animal = new Animal("Generic Animal");
$animal->eat();  // Output: Generic Animal is eating.

// Creating an instance of the Dog class
$dog = new Dog("Buddy");
$dog->eat();    // Output: Buddy is eating.
$dog->bark();   // Output: Buddy is barking.

In the above example, the Animal class has a property called $name and a method called eat().

The Dog class extends the Animal class using the extends keyword. It inherits the $name property and the eat() method from the Animal class. Additionally, the Dog class introduces a new method called bark().

By using inheritance, the Dog class can access the properties and methods of the Animal class without having to redefine them. This promotes code reuse and allows you to create more specialized classes based on existing ones.

In PHP, inheritance supports single inheritance, which means a class can only inherit from a single-parent class. However, you can create a hierarchy of classes by having child classes themselves act as parent classes for further derived classes.