PHP OOP Inheritance
Inheritance in OOP is when a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In PHP, we use the extends keyword to achieve this.
1. Parent and Child Classes
- Parent Class: The class whose properties and methods are inherited (also called Base or Super class).
- Child Class: The class that inherits from another class (also called Derived or Sub class).
2. Example: Using the extends Keyword
In this example, the Strawberry class inherits properties and methods from the Fruit class:
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message(); // Method from Child
$strawberry->intro(); // Method from Parent
?>
3. Overriding Inherited Methods
If a child class defines a method with the same name as one in the parent class, the child's method will "override" the parent's version. This is useful for changing behavior specifically for the child.
<?php
class Strawberry extends Fruit {
public function intro() {
echo "I am a Strawberry, and my name is {$this->name}.";
}
}
?>
4. The final Keyword
If you want to prevent a class from being inherited or a method from being overridden, you can use the final keyword.
<?php
final class Fruit {
// This class cannot be extended by any other class
}
class Fruit {
final public function intro() {
// This method cannot be overridden by children
}
}
?>
5. Protected Access and Inheritance
This is where protected properties shine. They cannot be accessed from outside the class, but they can be accessed by the child class.
Why use Inheritance? It follows the DRY (Don't Repeat Yourself) principle. You can define common behavior in a parent class (like User) and specific behaviors in child classes (like Admin or Customer).