Home >>PHP Object Oriented >PHP Polymorphism

PHP Polymorphism

Polymorphism in PHP

This word is can from Greek word poly and morphism. Poly means "many" and morphism means property which help us to assign more than one property. => Overloading Same method name with different signature, since PHP doesn't support method overloading concept => Overriding When same methods defined in parents and child class with same signature i.e know as method overriding

Method Overriding

<?php

class base

{

function add($a,$b)

{

$res=$a+$b;

echo "Sum of two number = ".$res;

}

}


class child extends base

{

function add($a,$b,$c)

{

$res=$a+$b+$c;

echo "Sum of three number = ".$res;

}

}

$obj= new child();

$obj->add(1000,500);
 
?>
Output Warning: Missing argument 3 for child::add(), called in C:xampplitehtdocsdboverriding.php on line 21 and defined in C:xampplitehtdocsdboverriding.php on line 13 Sum of three number = 1500
Eg ii
<?php

class base

{

function add($a,$b)

{

$res=$a*$b;

echo "Multiplication = ".$res;

}

}


class child extends base

{

function add($a,$b)

{

$res=$a+$b;

echo "Sum  = ".$res;

}

}

 $obj= new child();

 $obj->add(1000,500);
 
?>
Output Sum = 1500
In the above example class base have a method add with two signature the same method name with same signature defined in class child also. But when we call the method add( ) through object of its child, its own method have performed (addition of two number). It means child class add( ) method override its base class method add( ).

No Sidebar ads