Blog Details
Md. Raqibul Hasan
11 Oct 2024
2 min read
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.
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:
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.
Dog
inherits from Animal
.Car
can use different engines without changing how it works.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!
Don’t worry, we don’t spam!