PHP › Interfaces & Abstract Classes
How does the Liskov Substitution Principle relate to properly designing interfaces and abstract classes so that subclasses can genuinely be substituted for their parent type without breaking expected behavior?
AdvancedAnswer
The Liskov Substitution Principle states that objects of a subclass should be usable anywhere an object of the parent class or interface is expected, without altering the correctness of the program, meaning a subclass should honor the behavioral expectations established by its parent, such as not throwing unexpected exceptions for inputs the parent would have accepted, or not weakening guarantees the parent provided, and violating this principle, even while technically satisfying an interface's method signatures, can lead to subtle, hard to diagnose bugs when a specific subclass is substituted in.
// Violates Liskov Substitution Principle
class Bird { public function fly() {} }
class Penguin extends Bird {
public function fly() { throw new Exception('Penguins cannot fly'); }
}Real-world example A team refactors a class hierarchy after discovering that a Penguin subclass technically implemented a required fly method but simply threw an exception when called, violating the expectation established by the parent Bird class and causing unexpected failures wherever a generic Bird was expected.