Inheritance is a fundamental concept in object-oriented programming that allows to create new classes with properties and methods of existing classes. It promotes code reusability and helps to organize complex application systems.
To create a new class by inheriting from an existing class, with the use of extends
keyword:
It can access only public and protected properties and methods of the parent class.
Example:
// existing parent class
class ParentClass {
public function parentMethod() {
echo "Parent method";
}
}
// Creating new class by inheriting the properties and methods
class ChildClass extends ParentClass {
public function childMethod() {
echo "Child method";
}
}
To override a extended method in a child class to provide a specific implementation:
Example:
class Shape {
public function draw() {
echo "Drawing shape";
}
}
class Circle extends Shape {
public function draw() {
echo "Drawing circle";
}
}
- A child class can inherits all public and protected properties and methods from parent class.
- A child class can override extended methods of parent class.
- A child class can add own properties and methods.
- To access the parent class methods within the child class, Use
parent
keyword.