EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Polymorphism in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Polymorphism in PHP

Polymorphism in PHP

Introduction to Polymorphism in PHP

Polymorphism is one of the good concepts of the PHP Object Oriented Programming Language features (OOPS features). The word polymorphism is actually derived from the two Greek words “Poly” and “Morph”.  The meaning of poly is “many” and morph is “forms”. It means the ability to have many forms. In common terms, Polymorphism is an Object-Oriented Programming pattern in which the class is having various functionalities while having common interfaces. Actually Polymorphism is of two types: Compile-Time and Run-Time. PHP doesn’t support compile-time polymorphism which means function and operator overloading.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Class a{
//methods
Public function b(){
//methods
}
}
Class b extends a{
//methods
Public function b(){
//methods which are in/not in the function of the class a.
}
}

Explanation:

In the above syntax, we made 2 classes one is normal and the other one is to extend the class but we used the same function name/method for different functionalities. This is called poly morphing. One can use many similar names of functions/methods with different functionalities as needed in the coding.

Functions of Polymorphism in PHP

PHP’s Polymorphism works based on the run time polymorphism concept. In PHP, Polymorphism works by making the decision at runtime which is actually not a compile-time polymorphism concept or else we can say that we are having many/multiple implements which are subtype for a super class, runtime (function overloading) concept is an example of polymorphism of PHP Programming Language.

Function overloading means deriving a class from a newly created function with the same signature (it means the function is having the same name, same type and a number of arguments) in its parent class as a function which is called as method overriding. In this polymorphism concept, one can create functions by extending but the same name/ similar naming function should be involved in order to process the polymorphism and inheritance concept. In order to enhance the programming capability by increasing the class’s functionalities which having the common interfaces polymorphism is a must.

Examples to Implement Polymorphism in PHP

Below are the examples of Polymorphism in PHP:

Example #1

In the below example, one of the base class “Shap1” is created. Here we are going to inherit the Shap1 class in the three derived classes. The classes names are Circle1, Triangle1, and Elliipse1. Each and every class has the function draw in order to complete the runtime Polymorphism of PHP programming language. In the following calling process, here we are going to create an array with length 2 and every array’s index is helpful in creating an object of one class. After this, we are going to use a loop that is going to be executed based on the length of the array which is having a value “$i1” which is passing to the object array variable “$Val1[$i1]”. So it will be executed 3 times and it will be called using draw() method of each and every class.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Code:

<?php
class Shap1
{
function draw1(){}
}
class Circle1 extends Shap1
{
function draw1()
{
print "Circle1 has been drawn.\n";
}
}
class Triangle1 extends Shap1
{
function draw1()
{
print "Triangle1 has been drawn.\n";
}
}
class Ellipse1 extends Shap1
{
function draw1()
{
print "Ellipse1 has been drawn.";
}
}
$Val1=array(2);
$Val1[0]=new Circle1();
$Val1[1]=new Triangle1();
$Val1[2]=new Ellipse1();
for($i1=0;$i1<3;$i1++)
{
$Val1[$i1]->draw1();
}
?>

Output:

Polymorphism in PHP 1

Example #2

This is the example of the implementation of the Polymorphism concept with the interface help. Interface/interfaces are/are very similar to any class except which is not containing any code. The interface helps in defining the method names and also method arguments but here contents of the methods will not be defined. The interface which is executing by any class/classes must be executed by all the methods which are characterized by the interface.

Here Machine1 will have all classes to define calcTask1. Circle1 implements CallTask1() method. Rectangle1 also tries to implement a Machine interface but defines with a different body of calcTask1() method. Polymorphism says that all the methods which calculate the task should have an equivalent name. We are going to call the different names of calcTask1() without providing the details. Here the name of the method which calculates the task is important.

Code:

<?php
interface Machine1 {
public function calcTask1();
}
class Circle1 implements Machine1 {
private $radius1;
public function __construct($radius1){
$this -> radius1 = $radius1;
}
public function calcTask1(){
return $this -> radius1 * $this -> radius1 * pi();
}
}
class Rectangle1 implements Machine1 {
private $width1;
private $height1;
public function __construct($width1, $height1){
$this -> width1 = $width1;
$this -> height1 = $height1;
}
public function calcTask1(){
return $this -> width1 * $this -> height1;
}
}
$mycirc1 = new Circle1(3);
$myrect1 = new Rectangle1(3,4);
echo $mycirc1->calcTask1();
echo $myrect1->calcTask1();
?>

Output:

Polymorphism in PHP Example 2

Example #3

In the below example a class “base11” is created with a function add1() with $a1 and $b1 variables. Then “$res1” variable is created which is used to store the multiplication of the two variables “$a1” and “$b1” and the echo statement is used to print if the function is called. Then Child1 class is used to extend the base11 class. In the extended class, again add1() variable is created to store the sum or the a1 and b1 variables. Then a new object is created and called by passing the variable values to the values $a1 and $b1 variables.

Code:

<?php
class base11
{
function add1($a1,$b1)
{
$res1=$a1*$b1;
echo "Multiplication = ".$res1;
}
}
class child1 extends base11
{
function add1($a1,$b1)
{
$res1=$a1+$b1;
echo "Sum  = ".$res1;
}
}
$obj= new child1();
$obj->add1(1000,500);
?>

Output:

Polymorphism in PHP Example 3

Example #4

In the below example a class “BaseClass11” is created with the public function “myMethod()” is created with the echo statement to mention that “BaseClass11 method” is called that. Then again DerivedClass11 is created to extend the BaseClass11 with the same name function “myMethod()” with the echo statement to print “DerivedClass11 method called” like that. We are calling the same/similar naming function in different classes. Then new object is created for the function/ method “myMethod()”.

Code:

<?php
class BaseClass11
{
public function myMethod11()
{
echo "BaseClass11 method called";
}
}
class DerivedClass11 extends BaseClass11
{
public function myMethod11()
{
echo "DerivedClass11 method called";
}
}
function processClass11(BaseClass11 $c11)
{
$c11->myMethod11();
}
$c11 = new DerivedClass11();
processClass11($c11);
?>

Output:

DerivedClass Example 4

Recommended Article

This is a guide to the Polymorphism in PHP. Here we discuss the what is the definition of Polymorphism and its Working along with its examples as well as Code Implementation. You can also go through our other suggested articles to learn more-

  1. PHP Frameworks
  2. basename in PHP
  3. Validation in PHP
  4. print_r() in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More