0
0
PhpConceptBeginner · 3 min read

What is Inheritance in PHP: Explanation and Example

In PHP, inheritance allows a class to use properties and methods from another class, called the parent class. This helps reuse code and create a relationship where the child class extends the parent class's behavior.
⚙️

How It Works

Inheritance in PHP works like a family tree. Imagine a child learning skills from their parent. Similarly, a child class inherits properties and methods from a parent class, so it doesn't have to write the same code again.

This means the child class can use or change what it got from the parent. It can also add new features of its own. This makes programming easier and keeps code organized.

In PHP, you use the extends keyword to create this link between child and parent classes.

💻

Example

This example shows a parent class Animal with a method makeSound(). The child class Dog inherits from Animal and can use the same method.

php
<?php
class Animal {
    public function makeSound() {
        echo "Some generic sound\n";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "Bark!\n";
    }
}

$animal = new Animal();
$animal->makeSound(); // Outputs: Some generic sound

$dog = new Dog();
$dog->makeSound(); // Outputs: Bark!
Output
Some generic sound Bark!
🎯

When to Use

Use inheritance when you have classes that share common features but also have their own unique parts. For example, in a game, you might have a general Character class and specific classes like Wizard or Warrior that inherit from it.

This saves time because you write shared code once in the parent class. It also makes your code easier to update and understand.

Key Points

  • Inheritance lets a child class reuse code from a parent class.
  • Use the extends keyword to create inheritance.
  • Child classes can override parent methods to change behavior.
  • It helps keep code organized and reduces repetition.

Key Takeaways

Inheritance allows a class to reuse code from another class using the extends keyword.
Child classes can override parent methods to customize behavior.
It helps organize code and avoid repeating the same code in multiple places.
Use inheritance when multiple classes share common features but also have unique parts.