In PHP OOP, inheritance is a feature that allows a class to inherit properties and methods from another class. The class that inherits from another class is called the child class or subclass, and the class that is inherited from is called the parent class or superclass.
Here’s an example of a parent class and a child class:
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function eat() {
echo $this->name . " is eating.<br>";
}
public function sleep() {
echo $this->name . " is sleeping.<br>";
}
}
class Dog extends Animal {
public function bark() {
echo $this->name . " is barking.<br>";
}
}
$animal = new Animal("Animal");
$dog = new Dog("Dog");
$animal->eat(); // Output: Animal is eating.
$animal->sleep(); // Output: Animal is sleeping.
$dog->eat(); // Output: Dog is eating.
$dog->sleep(); // Output: Dog is sleeping.
$dog->bark(); // Output: Dog is barking.
In this example, the Animal
class is the parent class and the Dog
class is the child class. The Animal
class has a constructor that initializes the name
property, and two methods (eat()
and sleep()
) that output messages. The Dog
class extends the Animal
class using the extends
keyword, which means that it inherits all of the properties and methods of the Animal
class. It also has its own method (bark()
) that outputs a message.
To create an object of the Animal
class or the Dog
class, we use the new
keyword:
$animal = new Animal("Animal");
$dog = new Dog("Dog");
We can then access the properties and methods of both classes using the arrow (->
) operator:
$animal->eat(); // Output: Animal is eating.
$animal->sleep(); // Output: Animal is sleeping.
$dog->eat(); // Output: Dog is eating.
$dog->sleep(); // Output: Dog is sleeping.
$dog->bark(); // Output: Dog is barking.
In summary, inheritance in PHP OOP is a feature that allows a class to inherit properties and methods from another class. The child class can then add its own properties and methods, and override or extend the properties and methods of the parent class.