PHP / PHP Object-Oriented Programming (OOP)

Implementing Inheritance and Polymorphism

This tutorial will guide you through implementing inheritance and polymorphism in PHP. These are powerful OOP features that allow for efficient, modular, and maintainable code.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores object-oriented programming concepts in PHP.

Introduction

In this tutorial, our main goal is to learn how to implement inheritance and polymorphism in PHP. Inheritance is a mechanism that allows you to create a new class from an existing class. The new class inherits all the properties and methods of the existing class and can add new ones or modify the inherited ones. Polymorphism is the ability of an object to take on many forms, which allows us to perform a single action in different ways.

By the end of this tutorial, you will have learned:
- What inheritance and polymorphism are;
- How to implement inheritance and polymorphism in PHP.

Prerequisites
Basic understanding of PHP (variables, functions, classes) and familiarity with Object-Oriented Programming (OOP) concepts.

Step-by-Step Guide

Inheritance

In PHP, a class can be defined based on another class using the extends keyword. The class that is being extended is called the parent class, and the class that extends is called the child class.

Here's an example:

class ParentClass {
  protected $name;

  public function setName($name) {
    $this->name = $name;
  }
}

class ChildClass extends ParentClass {

  public function welcome() {
    return "Hello, " . $this->name;
  }
}

In this example, the ChildClass extends the ParentClass and inherits the $name property and the setName() method.

Polymorphism

Polymorphism in PHP can be achieved using interfaces. An interface defines a contract for what a class can do, without saying anything about how the class will do it. A class can implement an interface using the implements keyword.

Here's an example:

interface Shape {
  public function area();
}

class Circle implements Shape {
  protected $radius;

  public function __construct($radius) {
    $this->radius = $radius;
  }

  public function area() {
    return pi() * pow($this->radius, 2);
  }
}

class Square implements Shape {
  protected $length;

  public function __construct($length) {
    $this->length = $length;
  }

  public function area() {
    return pow($this->length, 2);
  }
}

In this example, Circle and Square are two different classes implementing the same interface Shape, but the area() method is implemented differently in both classes.

Code Examples

Inheritance

Here's an example of how we can use the child class and its inherited method.

$child = new ChildClass();
$child->setName("John");
echo $child->welcome();  // Outputs: Hello, John

Polymorphism

Here's an example of how we can use the polymorphism concept.

$circle = new Circle(3);
echo $circle->area();  // Outputs: 28.274333882308 (which is pi*radius^2)

$square = new Square(4);
echo $square->area();  // Outputs: 16 (which is side_length^2)

In this example, both Circle and Square classes are using the same method name area(), but the output is different based on the implementation.

Summary

In this tutorial, we have learned about inheritance and polymorphism in PHP. Inheritance allows us to create a new class from an existing one, inheriting its properties and methods. Polymorphism allows us to perform a single action in different ways.

Practice Exercises

  1. Exercise 1: Create a Vehicle parent class with a speed property and a setSpeed method. Then create Car and Bike child classes that inherit from the Vehicle class. Each child class should have a maximumSpeed method that prints a message with the maximum speed.

  2. Exercise 2: Create an interface Animal with a method makeSound. Implement this interface in the Dog and Cat classes. The makeSound method should return "Bark" for the Dog class and "Meow" for the Cat class.

  3. Exercise 3: Extend the Animal interface and add a eat method. Implement this method in both the Dog and Cat classes.

Solutions

  1. Solution for Exercise 1:
class Vehicle {
  protected $speed;

  public function setSpeed($speed) {
    $this->speed = $speed;
  }
}

class Car extends Vehicle {

  public function maximumSpeed() {
    return "The maximum speed of the car is " . $this->speed;
  }
}

class Bike extends Vehicle {

  public function maximumSpeed() {
    return "The maximum speed of the bike is " . $this->speed;
  }
}
  1. Solution for Exercise 2:
interface Animal {
  public function makeSound();
}

class Dog implements Animal {

  public function makeSound() {
    return "Bark";
  }
}

class Cat implements Animal {

  public function makeSound() {
    return "Meow";
  }
}
  1. Solution for Exercise 3:
interface Animal {
  public function makeSound();
  public function eat();
}

class Dog implements Animal {

  public function makeSound() {
    return "Bark";
  }

  public function eat() {
    return "The dog is eating.";
  }
}

class Cat implements Animal {

  public function makeSound() {
    return "Meow";
  }

  public function eat() {
    return "The cat is eating.";
  }
}

Keep practicing and implementing these concepts in your own projects to get a good grasp of them. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help