What is Inheritance in PHP?

Inheritance allows one class (child) to inherit methods and properties from another class (parent). It enables code reuse and simplifies code maintenance. PHP uses the extends keyword for inheritance. Child classes can also override parent methods. You can call parent methods using parent::methodName().

1. Basic Inheritance Example


class Animal {
    public function sound() {
        return "Some generic sound";
    }
}

class Dog extends Animal {
    public function bark() {
        return "Woof!";
    }
}

$pet = new Dog();
echo $pet->sound(); // Inherited from Animal
echo $pet->bark();  // From Dog

File: inheritance_basic.php

2. Overriding Parent Method


class Animal {
    public function sound() {
        return "Some sound";
    }
}

class Cat extends Animal {
    public function sound() {
        return "Meow";
    }
}

$cat = new Cat();
echo $cat->sound(); // Output: Meow

File: method_override.php

3. Using parent:: to Access Parent Method


class Animal {
    public function sound() {
        return "Animal sound";
    }
}

class Lion extends Animal {
    public function sound() {
        return parent::sound() . " and Roar!";
    }
}

$lion = new Lion();
echo $lion->sound(); // Output: Animal sound and Roar!

File: parent_method.php