Please wait

Inheritance (OOP Principle)

Inheritance is one of the four pillars of object-oriented programming. Before we dive into inheritance, I want to talk briefly about each fundamental concept.

Four Pillars of OOP

The four pillars of Object-Oriented Programming (OOP) are Encapsulation, Inheritance, Polymorphism, and Abstraction. These are fundamental principles used in many programming languages, including PHP. Let's break them down:

  • Encapsulation: This is the practice of keeping fields (properties or attributes) within a class private, so they can only be accessed and modified through methods (functions) in that class. This is also known as data hiding. It prevents outside code from accidentally changing the properties' values.
  • Inheritance: This allows a class to inherit the properties and methods of another class.
  • Polymorphism: This principle allows methods to do different things based on the object they are acting upon.
  • Abstraction: Refers to the idea of simplifying complex systems by modeling them with classes and objects that expose relevant properties and methods and hide unnecessary details.

These four principles provide a framework for organizing code in a way that is reusable, flexible, and easy to understand and maintain.

This book will dive into each of these concepts, starting with inheritance.

Diving into Inheritance

Inheritance in PHP is a fundamental concept of Object-Oriented Programming (OOP) that allows one class to inherit properties (variables) and methods (functions) from another class.

To help you understand, let's use a real-world example. Consider a general category like "Vehicle". All vehicles have certain common properties, like color and behaviors, and methods, like the ability to start or stop. In PHP, you might have a Vehicle class with properties such as $color and methods like start() and stop().

class Vehicle {
  public $color;
 
  public function start() {
    // code to start the vehicle
  }
 
  public function stop() {
    // code to stop the vehicle
  }
}

Now, say you want to create a more specific class, like Car. A car is a type of vehicle, so it should have all the properties and behaviors of a vehicle. But it also has additional properties and behaviors unique to cars. Rather than writing out all the vehicle properties and methods again, you can simply tell PHP that a "Car" is a type of "Vehicle".

This is done using the extends keyword. You must add this keyword after the class name and provide the name of the class to inherit from:

class Car extends Vehicle {
  public $numberOfDoors;
 
  public function lockDoors() {
    // code to lock the car doors
  }
}

Now, a Car object has the $color property, the start() method, and the stop() method from the Vehicle class, as well as the $numberOfDoors property and the lockDoors() method from the Car class. This is the power of inheritance - it allows you to reuse code, which makes your code shorter, easier to read, and easier to maintain.

Using properties from an inherited class

Using properties and methods from an inherited class (also known as a superclass or parent class) in PHP is straightforward. You just use them as if they were defined in the class itself.

First, here's how you'd create an instance of the Car class and use its properties and methods:

$myCar = new Car();
 
// Set the color property, inherited from Vehicle
$myCar->color = 'red';
 
// Set the numberOfDoors property, defined in Car
$myCar->numberOfDoors = 4;
 
// Call the start method, inherited from Vehicle
$myCar->start();
 
// Call the lockDoors method, defined in Car
$myCar->lockDoors();

In this example, $myCar is an instance of the Car class. You can use the -> operator to access properties and methods of the object.

The $color property and start() method are actually inherited from the Vehicle class, but you can use them just as if they were defined in the Car class. The $numberOfDoors property and lockDoors() method is defined in the Car class, so you can use them directly as well.

This is the beauty of inheritance: you can use properties and methods from the parent class just as if they were directly defined in the child class. This promotes code reusability and maintainability.

Using the $this keyword

The $this keyword in PHP is a reference to the current object. It's used to access the object's properties and methods from within the class definition.

In the context of inheritance, $this will provide access to all properties and methods of the current object, whether they are defined in the child class or inherited from the parent class.

Let's consider the Vehicle and Car classes from the previous examples and add some methods to demonstrate the use of $this:

class Vehicle {
  public $color;
 
  public function setColor($color) {
    $this->color = $color;
  }
 
  public function start() {
    // code to start the vehicle
  }
}
 
class Car extends Vehicle {
  public $numberOfDoors;
 
  public function setNumberOfDoors($numberOfDoors) {
    $this->numberOfDoors = $numberOfDoors;
  }
 
  public function displayCarDetails() {
    echo "This car is " . $this->color . " and has " . $this->numberOfDoors . " doors.";
  }
}
 
// Instantiate Car object
$myCar = new Car();
 
// Set properties using methods
$myCar->setColor("Red");
$myCar->setNumberOfDoors(4);
 
// Display car details
$myCar->displayCarDetails();  // Outputs: This car is Red and has 4 doors.

In this example, both setColor() and setNumberOfDoors() methods use $this to refer to the current instance of the Car class and set the respective properties. The displayCarDetails() method uses $this to access both the $color property (inherited from Vehicle) and the $numberOfDoors property (defined in Car) to print out a message about the car.

Parent Constructor method

If the parent class has a constructor method, but the child class does not, the parent's constructor will be called when an instance of the child class is created.

Here's an example:

class Vehicle {
  public $color;
 
  public function __construct($color) {
    $this->color = $color;
    echo "A new vehicle was created.\n";
  }
}
 
class Car extends Vehicle {
  public $numberOfDoors;
}

In this example, the Vehicle class has a constructor that sets the $color property and prints a message. The Car class extends Vehicle but does not define its own constructor.

If we attempt to create a new instance of the Car class without passing on an argument, we'll receive an error:

$myCar = new Car();  // Throws error
 

We must pass on an argument since the parent class has a parameter in the constructor method.

$myCar = new Car("Red");  // Outputs: A new vehicle was created.

Child Constructor method

If a child class has its own constructor method, that constructor will be called when an instance of the child class is created, not the parent's constructor.

class Vehicle {
  public $color;
 
  public function __construct($color) {
    $this->color = $color;
    echo "A new vehicle was created.\n";
  }
}
 
class Car extends Vehicle {
  public $numberOfDoors;
 
  public function __construct($numberOfDoors) {
    $this->numberOfDoors = $numberOfDoors;
    echo "A new car was created.\n";
  }
}
 
$myCar = new Car("Red", 4);
// Outputs: A new car was created.

In this example, when an instance of Car is created, the Car constructor is called. Inside the Car constructor, the Car constructor sets the $numberOfDoors property and echoes a message. So the output shows the message from the Car. However, the message from the Vehicle constructor message never appears in the output because PHP does not call it if a constructor method is present in the child class.

Using both parent and child constructor methods

If both the parent class and the child class have constructor methods, and you want to call both when creating an instance of the child class, you can do so using the parent::__construct() syntax within the child class's constructor.

The parent keyword refers to the class being inherited from the extends keyword. We can use the scope resolution operator (::) to invoke the __constructor() method.

class Vehicle {
  public $color;
 
  public function __construct($color) {
    $this->color = $color;
    echo "A new vehicle was created.\n";
  }
}
 
class Car extends Vehicle {
  public $numberOfDoors;
 
  public function __construct($color, $numberOfDoors) {
    parent::__construct($color);  // Call parent's constructor
    $this->numberOfDoors = $numberOfDoors;
    echo "A new car was created.\n";
  }
 
}
 
$myCar = new Car("Red", 4);
// Outputs:
// A new vehicle was created.
// A new car was created.

In this example, when an instance of Car is created, the Car constructor is called. Inside the Car constructor, the parent::__construct() call triggers the Vehicle constructor, setting the $color property and printing the first message. Then, the Car constructor sets the $numberOfDoors property and prints the second message. So the output shows that both constructors were called, in the order, Vehicle, then Car.

Key Takeaways

  • Inheritance is a core concept in Object-Oriented Programming (OOP) that allows one class (the child or subclass) to use the properties and methods of another class (the parent or superclass).
  • In PHP, inheritance is implemented using the extends keyword. If class B extends class A, B is the child class, and A is the parent class.
  • If a child class has its own constructor (__construct()), it will be called when an instance of the child class is created, not the parent's constructor.
  • The parent's constructor can be explicitly called within the child's constructor using parent::__construct().
  • Inheritance promotes code reusability and makes code easier to maintain, as common properties and methods can be defined once in a parent class and reused in any child class.
  • PHP supports single inheritance, meaning a class can extend only one other class. Extending multiple classes is not allowed.

Comments

Please read this before commenting