Blog Details
Inheritance vs.
Composition in PHP

Md. Raqibul Hasan
11 Oct 2024
2 min read
Inheritance vs. Composition
When writing code, two big ideas pop up: inheritance and composition. These ideas help us organize and reuse code. But what are they? Let’s break them down in simple terms.
What is Inheritance?
Inheritance is like a family tree. A class (child) gets all the traits from another class (parent). It’s a way to reuse code.
For example:
class Animal {
public function makeSound() {
echo "Some sound";
}
}
class Dog extends Animal {
// Dog gets the makeSound method from Animal
}
In this example, the Dog
class gets the makeSound
method from the Animal
class. This means we don’t have to write the same code twice.
Pros of Inheritance:
- Code reuse: You write a method once and use it in many classes.
- Easy to understand: It’s like a family tree where the child inherits traits.
Cons of Inheritance:
- Tight coupling: The child class is linked to the parent. Changes in the parent class can affect the child.
- Hard to scale: As your code grows, inheritance trees can become confusing.
What is Composition?
Composition is when one class uses another class inside it. Instead of a child inheriting from a parent, one class includes another as a part of it. It’s like building something with blocks.
For example:
class Engine {
public function start() {
echo "Engine started";
}
}
class Car {
public function __construct(private Engine $engine) {
}
public function startCar() {
$this->engine->start();
}
}
$car = new Car(new Engine());
$car->startCar(); // Outputs: Engine starts
Here, the Car
class uses an Engine
object. It doesn’t inherit from Engine
. Instead, it builds a relationship through composition.
Pros of Composition:
- Flexible: You can easily swap parts (like swapping the engine) without changing the entire class.
- Easier to scale: Adding new features is simple because parts are independent.
- Unit Testing: Unit testing is easy in composition because we know what all methods we are using from another class.
Cons of Composition:
- More setup: You may need to write more code to set things up.
- Can be harder to follow: For beginners, using many classes together might feel confusing.
When to Use Inheritance vs. Composition
- Use inheritance when classes are in a clear parent-child relationship. Example:
Dog
inherits fromAnimal
. - Use composition when you need flexibility and want to build things in parts. Example: A
Car
can use different engines without changing how it works.
Conclusion
Both inheritance and composition help us write cleaner code. Inheritance works when you need a clear family tree of classes. Composition is better for building things that need flexibility. Pick the right one based on your needs!