Method overloading

What is overloading?

Overloading in PHP provides means to dynamically create properties and methods.

“The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope”.

Note:- Php overloading is different than most object oriented languages.

In most object oriented languages
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

Php Overloading has two types
(i) Method Overloading
(ii) Property Overloading

What is Method Overloading?

Magic method __call() or __callStatic() invoked when method called by class object is not available in class.
PHP method overloading allows function call in both object and static context. The related magic functions are,
(i) __call() is triggered when invoking inaccessible methods in an object context.
(ii) __callStatic() is triggered when invoking inaccessible methods in a static context.

public __call ( string $methodname , array $arguments )
public static __callStatic ( string $methodname , array $arguments )

Why we need __call or __callStatic method?
Example:-

<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	
}
$emp = new Employee;
$emp->companyname("TCS");
?>
Output:- Call to undefined method Employee::companyname()

In this eg. companyname() method is not define in the class then show fatal error.

Now with the help of __call() we can solve this error.

<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	public function __call($methodname,$arg)
	{
	echo $methodname.' is '.$arg[0];	
	}
	
}
$emp = new Employee;
$emp->companyname("TCS");
$emp->companylocation("New Delhi");
?>
Output:- companyname is TCS
companylocation is New Delhi

In this eg we don’t need to create function companyname() and companylocation(), with the help of __call() method we can do this.

__callStatic method
if we want to call static method which is not define in class then we use this method.
In this example we are using __callStatic() so we donot need to create a object of the class and call the method with :: operator.

<?php
class Employee {
	public $empname;
	public $age;
	public function empinfo($empname,$age) {
		echo $empname.' age is '.$age;
	}
	public static function __callStatic($methodname,$arg)
	{
	echo $methodname.' is '.$arg[0];	
	}
	
}
Employee::companyname("TCS");
Employee::companylocation("New Delhi");
?>
Output:- companyname is TCS
companylocation is New Delhi

Property Overloading method show in magic method page.