Polymorphism – OOP PHP Tutorial

Date Posted: May 4, 2015, 8:42 am


In general, “Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms.

Most beginners would find the above description confusing, so let me give you real world example for you to better understand how it really works.

Let’s say we have a Dog, Cat and a Rabbit class. They’re all different but they all fall under the same category as Animal. So, it would make sense to create an interface named Animal and have all these classes implement it. That is basically Polymorphism, it’s a collection(interface) of classes that have many forms.

Assuming that we define Animal as a class instead of an interface, then forget about the Dog, Cat and Rabbit classes. The Animal class is very broad because there is so many kinds of Animal. Every animal is different, but they’re all categorized under Animal. Because of these you will have to create multiple conditional statements which makes a long and messy class that is not very efficient.

Instead of creating a class for a broad subject, you can create an interface for a bunch of different classes that run differently.

Example

Let’s use ‘Shape’ as our category:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

// Shape is the base class
interface Shape {
    // Define method(s) that will be used by classes who will be implementing this interface.
    public function getArea();
}

class Square implements Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function getArea(){
        return $this->width * $this->height;
    }
}

class Circle implements Shape {
    private $radius;

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

    public function getArea(){

        return $this->radius * $this->radius * 3.14;
    }
}

function calculateArea(Shape $shape) {
    return $shape->getArea();
}

echo calculateArea(new Square(5, 5)) . "<br/>";
echo calculateArea(new Circle(7));

Conclusion

Polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs.

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me