Inheritance in PHP
Inheritance in PHP is an object-oriented programming concept that allows a class (referred to as a subclass or child class) to inherit properties and methods from another class (referred to as a superclass or parent class). The primary goal of inheritance is to promote code reusability and establish a hierarchical relationship among classes, thereby creating a clear and manageable structure for complex applications.
```
class ParentClass {
// Properties
protected $property;
class ChildClass extends ParentClass {
// Additional properties and methods (if any)
public function extraMethod() {
echo “This is an extra method in ChildClass.”;
}
}
```
In this example, `ChildClass` extends `ParentClass` and thus inherits its properties and methods. The `ChildClass` can also have its own additional properties and methods, apart from those inherited from `ParentClass`.
```
class ParentClass {
public function displayMessage() {
echo “Message from ParentClass.”;
}
}
class ChildClass extends ParentClass {
public function displayMessage() {
echo “Message from ChildClass.”;
}
}
$child = new ChildClass();
$child->displayMessage(); // Outputs: Message from ChildClass.
```
In this example, the `displayMessage` method in `ChildClass` overrides the same method in `ParentClass`. When the `displayMessage` method is called on an instance of `ChildClass`, the overridden method is executed.
```
class ParentClass {
public function displayMessage() {
echo “Message from ParentClass.”;
}
}
class ChildClass extends ParentClass {
public function displayMessage() {
parent::displayMessage(); // Calls the parent class method
echo “ Additional message from ChildClass.”;
}
}
$child = new ChildClass();
$child->displayMessage(); // Outputs: Message from ParentClass. Additional message from ChildClass.
```
Here, `parent::displayMessage()` calls the `displayMessage` method from `ParentClass`, and then additional content is appended by the `ChildClass` method.
```
final class ParentClass {
// This class cannot be inherited
}
// or
class ParentClass {
final public function displayMessage() {
// This method cannot be overridden
}
}
```
```
abstract class AbstractClass {
abstract protected function displayMessage();
}
class ConcreteClass extends AbstractClass {
public function displayMessage() {
echo “Concrete implementation of abstract method.”;
}
}
```
In this example, `ConcreteClass` extends `AbstractClass` and provides an implementation for the abstract method `displayMessage`.