Polymorphism
About Polymorphism

Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms.Means we create same function in base and derived class.

In the case of polymorphism object invoke a function call decieded at runtime is call polymorphism.

Example 1:- To use of poymorphism

<?php
class base{
function show(){
echo "Inside the Base class<br/>";
}
}

class derived1 extends base{
function show(){
echo "Inside the Child class<br/>";
}
}

class derived2 extends base{

}

$obj=new base();
$obj->show();
$obj2=new derived1();
$obj2->show();
$obj3=new derived2();
$obj3->show();
?>

Output:-
Inside the Base class
Inside the Child class
Inside the Base class

Example 2:- To use of poymorphism

<?php
class base {
   public function test() {
      echo "BaseClass method called";
   }
}
 
class derived extends base {
   public function test() {
      echo "DerivedClass method called";
   }
}
 
function process(base $obj) {
   $obj->test();
}
 
$obj = new derived();
process($obj);
?>

Output:-
DerivedClass method called


Previous
Next