This question already has an answer here:
Clearly objective-C does not support function/method overloading, same as php. But anyone knows why these languages don't support this feature.
</div>
Objective-C does not support overloading as explained in that post
PHP5 supports overloading
You need a PHP version > 5.1.0
See PHP Documentation : http://php.net/manual/en/language.oop5.overloading.php
Actually PHP does support function overloading, but in a different way. PHP's overloading features are different from Java's:
PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
Checkout the following code blocks.
Function to find sum of n numbers:
function findSum() {
$sum = 0;
foreach (func_get_args() as $arg) {
$sum += $arg;
}
return $sum;
}
echo findSum(1, 2), '<br />'; //outputs 3
echo findSum(10, 2, 100), '<br />'; //outputs 112
echo findSum(10, 22, 0.5, 0.75, 12.50), '<br />'; //outputs 45.75
Function to add two numbers or to concatenate two strings:
function add() {
//cross check for exactly two parameters passed
//while calling this function
if (func_num_args() != 2) {
trigger_error('Expecting two arguments', E_USER_ERROR);
}
//getting two arguments
$args = func_get_args();
$arg1 = $args[0];
$arg2 = $args[1];
//check whether they are integers
if (is_int($arg1) && is_int($arg2)) {
//return sum of two numbers
return $arg1 + $arg2;
}
//check whether they are strings
if (is_string($arg1) && is_string($arg2)) {
//return concatenated string
return $arg1 . ' ' . $arg2;
}
trigger_error('Incorrect parameters passed', E_USER_ERROR);
}
echo add(10, 15), '<br />'; //outputs 25
echo add("Hello", "World"), '<br />'; //outputs Hello World
Object Oriented Approach including Method Overloading:
Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
Ref: http://php.net/manual/en/language.oop5.overloading.php
In PHP, overloading means you can add object members at run-time, by implementing some of the magic methods like __set
, __get
, __call
etc.
class Foo {
public function __call($method, $args) {
if ($method === 'findSum') {
echo 'Sum is calculated to ' . $this->_getSum($args);
} else {
echo "Called method $method";
}
}
private function _getSum($args) {
$sum = 0;
foreach ($args as $arg) {
$sum += $arg;
}
return $sum;
}
}
$foo = new Foo;
$foo->bar1(); // Called method bar1
$foo->bar2(); // Called method bar2
$foo->findSum(10, 50, 30); //Sum is calculated to 90
$foo->findSum(10.75, 101); //Sum is calculated to 111.75