Overloading in PHP and Overriding in PHP

Overloading in PHP

Overloading in PHP

Function overloading is a feature of object-oriented programming that allows creating more than one method with the same name but a different number of arguments parameter.
Overloading in PHP creates properties and methods dynamically.
Function overloading contains the same function name and that function performs different tasks according to the number of arguments.
In PHP function overloading is done with the help of magic function _call(). This function takes function name and arguments.

Use of Magic Function:

<?php

class filmyzilla
{
	function filmy($a)
	{
		echo "a=",$a;
	}
}
class filmywap extends filmyzilla
{
	function filmy($b,$c)
	{
		echo "<br>b=",$b,"<br>c=",$c;
	}
}
$ob=new filmywap();
$ob->filmy(1);
$on->filmy(2,3);
?>
Output:
Warning: Declaration of filmywap::filmy($b, $c) should be compatible with filmyzilla::filmy($a)

From the above example, we can say that in PHP
overloading with the same name function can't be possible. Therefore, with the help of magic function overloading is done in PHP.
<?php
class Addiiton
{
	function __call($nam,$a)
	{
		if($nam=='add')
		{
			switch (count($a)) {
				case 1:
					return $a[0];
					break;
				case 2:
					return $a[0]+$a[1];
					break;	
				case 3:
					return $a[0]+$a[1]+$a[2];
					break;	
				
				default:
					echo "Invalid Arguments";
					break;
			}
		}
	}

}

$s=new Addiiton();
echo $s->add(1);
echo "<br>".$s->add(2,3);
echo "<br>".$s->add(4,5,6);

?>
Output:
1
5
15

Overriding in PHP
In function overriding, both parent and child classes should have the same function name and number of arguments.
It is used to replace the parent method in child class.

The purpose of overriding is to change the behavior of the parent class method.

The two methods with the same name and the same parameter are called overriding.

Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
<?php
class Addiiton
{
	function __call($nam,$a)
	{
		if($nam=='add')
		{
			switch (count($a)) {
				case 1:
					return $a[0];
					break;
				case 2:
					return $a[0]+$a[1];
					break;	
				case 3:
					return $a[0]+$a[1]+$a[2];
					break;	
				
				default:
					echo "Invalid Arguments";
					break;
			}
		}
	}

}

$s=new Addiiton();
echo $s->add(1);
echo "<br>".$s->add(2,3);
echo "<br>".$s->add(4,5,6);

?>
Output:
Parent
Child

Comments