Home > Article > Backend Development > Composition vs. Inheritance
Inheritance vs. Composition in PHP ?
When we program object-oriented, it is important to understand the difference between Inheritance and Composition:
Inheritance
One class inherits from another, reusing and extending its behavior.
class Motor { public function ligar() { return "Motor Ligado!"; } } class Carro extends Motor{} $carro = new Carro(); $carro->ligar();
Composition
A class contains instances of other classes to delegate responsibilities. Composition is often preferred to create more flexible systems and avoid problems with deep inheritance.
Practical Example
Have you ever stopped to think that when we start the car, we are actually starting the engine? Following this reasoning, we can create two objects: one called Engine and another called Car. This way, the Car object will contain an instance of the Engine object, which will be responsible for starting the car.
Code
class Motor { public function ligar() { return "Motor Ligado!"; } } class Carro { private Motor $motor; public function __construct(Motor $motor) { $this->motor = $motor; } public function ligar() { return $this->motor->ligar(); } }
Understanding
Instead of the Car class having the logic for starting the engine directly built in, it delegates this responsibility to an Engine object. This keeps the Car class focused on just what it is supposed to do, making the code more modular and easier to maintain. In the future, you can change or improve the engine without modifying the Car class code.
Testing
$motorV4 = new Motor(); $carro = new Carro($motorV4); echo $carro->ligar(); // Saída: Motor Ligado!
Advantages
This approach is more flexible because it allows the car to have different engine types (for example, a V4, V6, or electric engine) without having to change the Car class. This modularity facilitates system maintenance and expansion.
The above is the detailed content of Composition vs. Inheritance. For more information, please follow other related articles on the PHP Chinese website!