Function overloading and overriding in PHP


Function Overloading: Function overloadingcontains the same function name, and this function performs different tasks depending on the number of arguments. For example, find an area of ​​certain shapes where the radius is given, then it should return the area of ​​the circle, if the height and width are specified, then it should give the area of ​​the rectangle and others. Like other OOP languages, function overloading cannot be done natively. In PHP, function overloading is done using the __call() magic function. This function takes a function name and arguments.Example :
// PHP program to explain the function
// PHP overload 
// Create a shape class class shape { // __call is a magic function that takes // function name and arguments function __ call ( $name_of_function , $arguments ) { // will match the function name if ( $name_of_function == 'area' ) { switch ( count ( $arguments )) { // If there is only one argument // area of ​​the circle case 1: return 3.14 * $arguments [0]; // If two arguments, area is rectangel; case 2: return $arguments [0] * $arguments [ one]; } } }}  
// Declaring a shape type object $s = new Shape;  
// Function call echo ( $s -> area (2)); echo "" ;  
// call area method for rectangel echo ( $s -> area (4, 2)); ?>
6.28 8 
Overriding functions: Overridingfunctions is the same as in other OOP programming languages. In function overrides, parent and child classes must have the same function name with number of arguments and number. It is used to replace the parent method in the child class. The purpose of overriding is to change the behavior of a parent class method. Two methods with the same name and the same parameter are called overrides.Example : < ? php
// PHP program to implement
// function override  
// This is the parent class class P { // Parent class engineer function function engineer() { echo "Parent" ; } }  
// This is a child class class C extends P { // Geek method override function engineer() { echo "Child" ; } }  
// Parent reference type $p = new P;  
// Descendant reference type $c = new C;  
// Parent print $p -> engineer();  
// Print the child $c -> engineer(); ?>
Parent Child 

Get Solution for free from DataCamp guru