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.
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
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.