Open In App

What is Inheritance in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Inheritance is a fundamental object-oriented programming concept in PHP where a class (subclass or child class) can inherit properties and methods from another class (superclass or parent class). It enables code reusability and promotes hierarchical relationships between classes.

Syntax:

// Parent class
class Animal {
public $species;

public function sound() {
return "Animal makes a sound.";
}
}

// Child class inheriting from Animal
class Dog extends Animal {
public function sound() {
return "Dog barks.";
}
}

Explanation: To implement inheritance in PHP, use the extends keyword followed by the name of the parent class. The child class inherits all public and protected properties and methods from the parent class.

Accessing Parent Class Members:

  • Child classes can access parent class properties and methods using the parent:: keyword.

Constructor in Inheritance:

  • Child classes can have their own constructors, which can optionally call the parent class constructor using parent::__construct( ).

Single Inheritance:

  • PHP supports single inheritance, meaning a class can inherit from only one parent class at a time.

Multiple Inheritance:

  • PHP does not support multiple inheritance where a class can inherit from multiple parent classes simultaneously.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads