PHP Inheritance is a fundamental concept in object-oriented programming (OOP) within the PHP language. It allows classes to inherit methods, properties, and behaviors from other classes, promoting code reusability and establishing a hierarchical relationship between classes.
Inheritance in PHP was introduced in PHP 4, which marked the language's initial steps towards supporting OOP. However, PHP 4's implementation was limited. The true power of inheritance and OOP in PHP came with PHP 5, released in July 2004. PHP 5 introduced features like:
These enhancements made PHP's OOP model more robust, closely aligning with other object-oriented languages like Java or C#.
extends
to indicate inheritance. For example:
class ParentClass {
// Parent class properties and methods
}
class ChildClass extends ParentClass {
// Child class can use parent methods and add new ones
}
public
: Accessible from anywhere.protected
: Accessible within the class itself and by inherited and parent classes.private
: Accessible only from within the class itself.parent::__construct()
.Many PHP frameworks like Laravel or Symfony extensively use inheritance to create a structured and extensible codebase: