Function Overloading in PHP
Function overloading is a feature that permits making creating several methods with a similar name that works differently from one another in the type of the input parameters it accepts as arguments.
Example
Let us now see an example to implement function overloading−
<?php class Shape { const PI = 3.142 ; function __call($name,$arg){ if($name == 'area') switch(count($arg)){ case 0 : return 0 ; case 1 : return self::PI * $arg[0] ; case 2 : return $arg[0] * $arg[1]; } } } $circle = new Shape(); echo $circle->area(3); $rect = new Shape(); echo $rect->area(8,6); ?>
Output
This will produce the following output−
9.42648
Function Overriding in PHP
In function overriding, the parent and child classes have the same function name with and number of arguments
Example
Let us now see an example to implement function overriding−
<?php class Base { function display() { echo "\nBase class function declared final!"; } function demo() { echo "\nBase class function!"; } } class Derived extends Base { function demo() { echo "\nDerived class function!"; } } $ob = new Base; $ob->demo(); $ob->display(); $ob2 = new Derived; $ob2->demo(); $ob2->display(); ?>
Output
This will produce the following output−
Base class function! Base class function declared final! Derived class function! Base class function declared final!