Function overloading and Overriding in PHP
Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments.
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.
Example:
php
<?php
class shape {
function __call( $name_of_function , $arguments ) {
if ( $name_of_function == 'area' ) {
switch ( count ( $arguments )) {
case 1:
return 3.14 * $arguments [0];
case 2:
return $arguments [0]* $arguments [1];
}
}
}
}
$s = new Shape;
echo ( $s ->area(2));
echo "\n" ;
echo ( $s ->area(4, 2));
?>
|
Function Overriding: Function overriding is same as other OOPs programming languages. In function overriding, both parent and child classes should have same function name with and number of arguments. It is used to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The two methods with the same name and same parameter is called overriding.
Example:
php
<?php
class P {
function geeks() {
echo "Parent" ;
}
}
class C extends P {
function geeks() {
echo "\nChild" ;
}
}
$p = new P;
$c = new C;
$p ->geeks();
$c ->geeks();
?>
|
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Last Updated :
18 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...