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

How to Rename Column Name in SQL
46651
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
900972
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
51012
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
908387
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34525
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902194
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
25564
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
3842
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

OOP Concepts and Examples That Every Programmer Should Know
25126
In this article, we will cover the basic concepts around Object-Oriented Programming and discuss the commonly used terms: Abstraction, Encapsulation,
Read More

by Rohan Vats

26 Feb 2024

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