Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
inheritance
communitycreator

What is class Inheritance in PHP?

NDUKWE CHIDERA K.

In object-oriented programming (OOP), fundamental concepts define our understanding of the whole process. Such concepts which concern us directly in this shot include classes, objects, properties and methods.

Class

Classes are blueprints for the creation of objects. They provide the layout with which objects can be created. For example, a footwear class.

Object

An object is an instance of a class. It has access to all properties of the class and can even have more for itself. The footwear class from the example above can have objects like shoe, sandals, flip-flops, etc.

Property

Properties are the attributes of a class or an object. For example, the footwear class can have the general attributes of sole, color, size, and so on. The objects can have all of the class attributes, and some specific ones like the sandals object can have the buckle attribute.

Method

Methods are the actions/functions with which a class or an object is associated. They are the actions that they perform. Functions in a class are also accessible by its objects. Our footwear class can have the cleaning method, wearing method, age method, and so on.

Moving on, let’s now talk about inheritance.

Inheritance

In PHP, classes are declared with the class command while objects are declared with the new keyword. Inheritance is initialized using the extends keyword.

Inheritance is a concept in PHP OOP, where classes are created out of another class. Simply put, it means to derive one class from another.

The main class is called the parent class, and the derived class the child class. The child class inherits all the public properties of the parent class and can have its own methods and properties.

From our footwear class, a new class boot can be created. This new class will inherit all the properties and methods of the footwear class. Let’s look at an example of inheritance in the code below.

Code

<?php
//parent class footwear
class footwear {
  public $color;
  public $size;
  public function __construct($color, $size) {
    $this->color = $color;
    $this->size = $size;
  }
  public function meet() {
    echo "Footwear color is {$this->color} and size is  {$this->size}.";
  }
}

// boots is inherited from footwear
//child class footwear
class boot extends footwear {
  public function meetresult() {
    echo "boot is in its own class, ";
  }
}
$shoes = new boot("black", "10");
$shoes->meetresult();
$shoes->meet();
?>
Inheritance

Conclusion

Inheritance is a useful OOP concept that allows for component and code reuse, which helps us write minimal code and achieve fantastic results.

RELATED TAGS

php
inheritance
communitycreator
RELATED COURSES

View all Courses

Keep Exploring