In PHP, inheritance is an important feature of object-oriented programming that allows developers to reuse properties and methods from parent classes by creating subclasses. Inheritance not only reduces code duplication but also improves code maintainability and scalability.
In the following example, we will demonstrate how inheritance works in PHP by creating an Animal parent class and a Cat subclass that inherits from it.
First, we define a parent class. In this example, we will create a class named Animal, which contains a property called name and a method eat() :
class Animal {
protected $name;
public function eat() {
echo "The animal is eating.";
}
}
In the above code, we use the protected access modifier for the $name property. This means the child class can access this property.
Next, we will create a subclass called Cat and have it inherit from the Animal class, including its properties and methods:
class Cat extends Animal {
public function meow() {
echo "The cat is meowing.";
}
}
In this example, the Cat class inherits all properties and methods from the Animal class. Additionally, we have defined a new method, meow().
Next, let's create a Cat object and call both the inherited method from the Animal class and the method defined in the Cat class:
$cat = new Cat();
$cat->eat(); // Inherited method
$cat->meow(); // Custom method
In the code above, we first create a Cat object. Then we call the eat() method inherited from the Animal class and the meow() method defined in the Cat class.
Within a child class, we can also use the parent keyword to access properties and methods from the parent class. Here's an example:
class Cat extends Animal {
public function eat() {
parent::eat(); // Call the eat() method from the parent class
echo "The cat is also eating.";
}
}
In this example, within the Cat class's eat() method, we use parent::eat() to call the eat() method from the parent class Animal. This allows the child class to call a parent method while also defining its own behavior.
Inheritance is a key feature of object-oriented programming that allows subclasses to inherit properties and methods from parent classes. It promotes code reuse and extension. Through inheritance, child classes can reuse parent class code and also extend or customize their functionality.
In this article, we've covered the basics of inheritance in PHP. We created a parent class Animal and a subclass Cat, which inherited from Animal. We also showed how to create objects and call inherited methods, as well as how to use the parent keyword. We hope this article helps you understand inheritance in PHP and apply it effectively in your own development.