Programming Concepts
Intermediate
What is Composition over Inheritance?
A design principle favoring object composition (has-a relationships) over class inheritance (is-a relationships) for code reuse.
Composition over inheritance advises building complex behavior by combining simple, focused objects rather than creating deep inheritance hierarchies. Inheritance creates tight coupling between parent and child classes, and deep hierarchies become fragile — changing a base class can break all descendants. Composition is more flexible: behaviors can be mixed and matched at runtime, components can be replaced independently, and testing is simpler (mock individual components). In PHP, traits provide a limited form of composition within the class system. The Strategy pattern exemplifies composition — injecting different algorithm implementations rather than subclassing for each variation.