Published in PHP
Inheritance vs Composition with PHP Examples
By Atakan Demircioğlu
Fullstack Developer
My notes about composition, and inheritance on the PHP side.
composition-inheritance-php
Inheritance vs Composition with PHP Examples
My notes about composition, and inheritance on the PHP side.
Inheritance In PHP
- Basically, the child class will inherit all the public and protected properties and methods from the parent class (w3)
- Inheritance creates a dependency between child and parent and this breaks the encapsulation
- An inherited class is defined by using the extends keyword
- It is an IS-A relationship
- Inheritance is not the right tool for reusing the code pieces
- final keyword can be used to prevent class inheritance (final class Payment)
- final keyword can be used to prevent method overriding
- It can cause to inherit of useless methods and properties
- In conclusion, by using inheritance to reuse the code here, we also introduce a tightly coupled, non-flexible, redundant, complex, and does not make sense object.
Composition In PHP
- Basically, allows one class to contain another.
- It is a HAS-A relationship
- A good way for code reuse
- Writing Unit tests are much easier
- More flexible
- More loosely coupled structure that avoids a fragile hierarchy of classes.