为什么Objective-C、PHP不支持方法重载


Why Objective-C,PHP do not support method overloading?

很明显,objective-C不支持函数/方法重载,就像php一样。但是任何人都知道为什么这些语言不支持这个功能。

Objective-C不支持如后中所解释的重载

PHP5支持过载

您需要的PHP版本>5.1.0
请参阅PHP文档:http://php.net/manual/en/language.oop5.overloading.php

实际上PHP确实支持函数重载,但方式不同。PHP的重载特性与Java的不同:

PHP对"重载"的解释与大多数面向对象语言不同。重载传统上提供了具有相同名称但参数数量和类型不同的多个方法的能力。

签出以下代码块。

求n个数之和的函数:

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

包括方法重载的面向对象方法:

PHP中的重载提供了动态"创建"属性和方法的方法。这些动态实体通过魔术方法进行处理,可以在一个类中为各种动作类型建立魔术方法。

参考编号:http://php.net/manual/en/language.oop5.overloading.php

在PHP中,重载意味着您可以在运行时通过实现__set__get__call等神奇方法来添加对象成员。

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