Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconPolymorphism in PHP Explained [With Examples]

Polymorphism in PHP Explained [With Examples]

Last updated:
19th Feb, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Polymorphism in PHP Explained [With Examples]

The PHP programming language follows an object-oriented programming (OOP) paradigm, along with other base structures. One of the most significant features of OOPs is polymorphism. In general terms, polymorphism is derived from Greek words poly meaning many and morphism meaning forms. Polymorphism in OOPs is a concept that allows you to create classes with different functionalities in a single interface.

Generally, it is of two types: compile-time (overloading) and run time (overriding), but polymorphism in PHP does not support overloading, or in other words, compile-time polymorphism. The most significant benefit of polymorphism in PHP is that you don’t have to worry about the technicalities of defining which code is written in which class, as all will be used in the same way.

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

An easy-to-understand example of object-oriented PHP polymorphism is the area of different geometric shapes. There are many shapes with different lengths, widths, radius, and other parameters, but all the figures will have an area. Don’t worry if you didn’t understand it, as we will look at various polymorphism examples in PHP to understand better the concept and how to implement it.

Ads of upGrad blog

Check out upGrad’s Advanced Certification in Blockchain

What is Polymorphism in PHP?

Polymorphism in PHP is a fundamental component of object-oriented programming (OOP) which enables objects of several classes to be viewed as objects of a single superclass. This allows for flexibility in the way methods are implemented, allowing several classes, each with their unique implementation, to utilize the same method name. This idea is accomplished by inheritance and method overriding, which allow a subclass to modify a superclass method to fit its unique needs while preserving a shared interface. Polymorphism in PHP examples illustrate how by permitting the usage of common interfaces and abstract classes, polymorphism facilitates code reuse. By simplifying the code structure and enabling more flexible code design, it also increases readability and maintainability. It facilitates the development of modular and extensible software systems by PHP programmers, resulting in the creation of more scalable and efficient code. PHP supports polymorphic behavior by establishing abstract classes or common interfaces, which let subclasses provide their implementations while still abiding by the superclass’s contract. 

Types of PHP polymorphism  

There are typically two forms of polymorphism: 

  • Polymorphism using abstract classes 

PHP’s abstract classes give you the ability to specify the blueprints for other classes. They may have one or more abstract methods that must be implemented by any subclass and are not directly instantiable.  

Syntax: 

Abstract parent – class {   

  Statement . . .   

  . . . . . . . .    

  Abstract function ()   

  . . . . . . . .   

}   

Child – class extends parent – class {   

  Statement . . .   

  . . . . . . . .    

}  

  • Polymorphism using Interface 

PHP interfaces give you a means to specify a contract that classes must abide by. By considering several objects as instances of the same interface, multiple classes that implement the same interface can allow for polymorphism. As a result, objects of various classes can be utilized interchangeably provided they implement the same interface-defined functions. 

Syntax: 

interface InterfaceName { 

    // Method declarations without implementation 

    public function method1(); 

    public function method2(); 

} 

class ClassName implements InterfaceName { 

    // Implementation of interface methods 

    public function method1() { 

        // Method implementation 

    } 

    public function method2() { 

        // Method implementation 

    } 

} 

How to Implement Polymorphism in PHP?

Polymorphism in PHP can be implemented by either the use of interfaces or abstract classes. We will look at examples to enforce it in both ways.

Polymorphism Example in PHP to Implement in Interfaces

You can consider the interface as a blueprint for all the classes that extend it. They are similar to classes with just a single primary difference. You can declare and define method names and arguments within interfaces, but you cannot write method code. Any class implementing an interface will implement all its methods. The syntax of an interface is:

Check out upGrad’s Advanced Certification in Cloud Computing

interface exampleInterface{

public function methodName();

}

Since now you know about interfaces, let’s look at how to implement polymorphism in PHP in an interface.

<?php

interface ShapeExmp{

public function calcArea();

}

class SquareExmp implements ShapeExmp{

      private $side;

public function __construct($side){

$this->side = $side;

}

   public function calcArea(){

$area = $this->side * $this->side;

echo “Area of square = “.$area;

}

}

class RectangleExmp implements ShapeExmp{

private $width1;

private $height1;

public function __construct($width1,$height1){

$this->width1 = $width1;

$this->height1 = $height1;

   }

public function calcArea(){

$area = $this->width1 * $this->height1;

echo “<br>Area of rectangle = “.$area;

   }

}

class TriangleExmp implements ShapeExmp{

private $cons1;

private $width1;

private $height1;

public function __construct($cons1,$width1,$height1){

$this->cons1 = $cons1;

$this->width1 = $width1;

$this->height1 = $height1;

   }

public function calcArea(){

$area = $this->cons1 * $this->width1 * $this->height1;

echo “<br>Area of triangle= “.$area;

   }

}

$squ = new SquareExmp(8);

$squ->calcArea();

$rect = new RectangleExmp(10,15);

$rect->calcArea();

$tri = new TriangleExmp(0.5,10,12);

$tri->calcArea();

?>

Output:

Area of square = 64

Area of rectangle = 150

Area of triangle= 3

As you can see in the above example, we have implemented polymorphism in PHP through an interface. We have constructed and got the area of three shapes: square, triangle, and rectangle. The implemented classes keep on changing, and the arguments too, but the result is always the shape’s area. Similarly, you can also construct and calculate the area of other shapes such as circles, parallelograms, ellipse, and more.

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Polymorphism Example in PHP to Implement in Abstract Classes

Abstract classes in PHP are the parent classes that have methods defined but not the code. They are defined with the help of the “abstract” keyword. You can only use them to inherit other classes. Every abstract class has one or more abstract methods. These classes require their child classes to fill the methods with the same name. Hence, different child classes use the methods, in the same way, thereby implementing polymorphism in PHP. Let’s better understand this with a polymorphism example in PHP.

<?php

abstract class shapeExmp{

abstract protected function calcArea();

}

class rectangleExmp extends shapeExmp{

var $x,$y;

public function __construct($x , $y){

$this->x=$x;

$this->y=$y;

}

public function calcArea(){

$a=$this->x*$this->y;

return $a;

}

}

class circleExmp extends shapeExmp{

var $r;

public function __construct($r){

$this->r=$r;

     }

public function calcArea(){

$pi=3.142;

$a=pow($this->r,2)*$pi;

return $a;

     }

}

class squareExmp extends shapeExmp{

var $s;

public function __construct($s){

$this->s=$s;

     }

public function calcArea(){

$a=$this->s * $this->s;

return $a;

     }

}

$rect=new rectangleExmp(8,10);

$area=$rect->calcArea();

echo “Rectangle area= $area <br>”;

$circ=new circleExmp(5);

$area=$circ->calcArea();

echo “Cirlce area=$area<br>”;

$squ=new squareExmp(7);

$area=$squ->calcArea();

echo “Square area= $area <br>”;

?>

Output:

Rectangle area= 80

Circle area=78.55

Square area=49

As you can see in the above example, we first created an abstract class shapeExmp. We then defined an abstract function calcArea() in it. To calculate the circle, rectangle, and square area, we derived those classes from the abstract class and used the abstract function calcArea(). Similarly, you can use the abstract classes to implement polymorphism in PHP and use it during run time.

In-Demand Software Development Skills

Checkout: PHP Projects on Github

Ads of upGrad blog

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

This would have cleared all your doubts about polymorphism in PHP. You can try using it in different ways with the help of any IDE or online PHP compiler. PHP has grown to become a prevalent programming language. There are numerous career opportunities available in PHP. It is well suited for interactive web development and essential to learn to become a full-stack developer.

If you want to pursue a full-stack development career, you can check out upGrad and IIIT-B’s Executive PG Program in Full-stack Software Development course. The course offers you education on 16 different programming languages and tools. With 9+ project assignments to complete during the course, upGrad gives you placement assurance. It offers you 500+ hours of training materials to help you learn how to build robust and scalable websites and applications.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is object-oriented programming?

2What is polymorphism in programming?

Polymorphism is the ability to have more than one form. For example, a dog has 4 legs but the legs are different. This is a different form of the same object. In computer programming, polymorphism is the ability to have different inputs and have a single output. For example, we can have a class of Person, Worker, and Customer and each individual has different inputs. They have different inputs as each person has different name, address, and phone number. However, the output is the same for all of them which is the class of Person.

3How do classes and objects work in programming?

Classes are a fundamental unit of object-oriented programming (OOP). They're blueprints for objects, and as such they're used to create objects and to define the behavior of objects. Classes can be thought of as the universal building blocks of OOP. They're used to create objects that are specific for a particular task or situation. Unlike the real world, however, classes can be created at almost any time, and in any order. You can create a class even before you know how it will be used - a process known as “anonymous” class instantiation.

Explore Free Courses

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902297
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43494
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
230000
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon