function overriding in php

Function Overloading: Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments.

Function Overloading and Overriding in PHP

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.

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();
?>

Method overriding allows a child class to provide a specific implementation of a method already provided by its parent class.

To override a method, you redefine that method in the child class with the same name, parameters, and return type.

The method in the parent class is called overridden method, while the method in the child class is known as the overriding method. The code in the overriding method overrides (or replaces) the code in the overridden method.

PHP will decide which method (overridden or overriding method) to call based on the object used to invoke the method.

If an object of the parent class invokes the method, PHP will execute the overridden method.
But if an object of the child class invokes the method, PHP will execute the overriding method.
Let’s take an example to understand method overriding better.

The following example defines the Robot class that has one public method greet() and the Android class that inherits the Robot class:

42