Complete Guide to function overriding in PHP

0
174
Complete Guide to function overriding in PHP

In this article, you going to see in detail regarding what is function overriding in PHP with example explained in a simple way.

If you are looking for this topic then you are at a right place, you will get all the information in depth.

Let’s start with the topic of function overriding in PHP

Function overriding is OOP's concept in PHP

Function overriding is used when the class has some methods and the derived class wants the same methods with different behavior.

In function overriding, both parent and child classes should have the same function name and number of arguments.

With the help of this overriding concept you can change the behavior of parent class.

The main definition of overriding is the two methods which having same name and the same parameter.

Below is the example from which you can understand easily.

<?php
class Foo {
   function myFoo() {
      return "Foo";
   }
}
class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}
$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); 
echo($bar->myFoo()); 
?>

There is also one more important OOP's a concept which you should know regarding this, which is called function overloading which can be achieved with the help of the magic _call() function.

Below we going to see the difference between both topic of overloading and overriding.

what are the difference between function overloading and function overriding in PHP

Function overloading contains the same function name.

That function do different task according to the parameter or arguments passed.

And the important point regarding overloading is that it can be achieved using magic _call() function.

Below is example of overloading from which you can understand completely.

<?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, 4)); 



?>

In case of Function overriding, it is a two method with same name and same parameter is called overriding.

One of the Best Example is explained above for function overriding.

Conclusion:

Finally, we have done with discussion regarding function overriding in PHP.

I hope you like this article and if you feel like we missed out on anything, please comment below.