Function Overloading And Overriding In PHP

 


Function overloading and overriding is the Object Oriented Programming feature in PHP. Function overloading means multiple function have the same name but different parameters. But in case of function overriding, more than one functions will have same method signature and number of arguments.

PHP doesn’t support function overloading directly like other languages such as C++, JAVA etc. But we can overcome this issue with using the PHP magic method __call(). So let’s see how overloading and overriding in PHP works.

Function Overloading In PHP

Function overloading contains same function name and that function performs different task according to number of arguments.

Example

<?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
48

Function Overriding In PHP

Function overriding in PHP is quite easy. Overriding is the process of modifying something of the inherited method. Means in function overriding, the parent and child classes have the same function name with and number of arguments

In belwo example you see two classes Base and Derived. Derived cass extends to Base. Which means Derived can access parent class. Here you see parent has demo() function and child class also demo() function with same name and same argument. Here you see function overriding scenario where child class override the base class function.

<?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!

Original article publish here.>>

Most Popular

Connect to Amazon EC2 instance using Filezilla and SFTP

About PHP language & CodeIgniter

Reset the auto increment value for a MySQL table