How does inheritance in PHP help in avoiding code duplication and promoting code reusability?
Inheritance in PHP allows a child class to inherit properties and methods from a parent class, reducing the need for code duplication. By creating a parent class with common functionality, child classes can extend this class and inherit its behavior, promoting code reusability and maintaining a DRY (Don't Repeat Yourself) codebase.
class ParentClass {
protected $sharedProperty;
public function sharedMethod() {
// Common functionality shared by child classes
}
}
class ChildClass extends ParentClass {
// Child class inherits properties and methods from ParentClass
}