0

During my programming life in PHP, whenever I create function in PHP with same name, but different parameters this was cause error. Because of that I'm wondering did PHP has any kind of function overloading feature, and if it have I would appreciated to show me an example.

Thanks.

zajke
  • 1,675
  • 2
  • 12
  • 13

1 Answers1

1

Simply put: no. In PHP, a method signature doesn't include it's parameter set, only it's name. Therefore, two methods with the same name but different parameters are actually considered equal (and thus an error results).

PHP does have a different process which it calls method overloading, but it's a different approach to the problem. In PHP, overloading is a means by which methods and properties can be dynamically created on an object at runtime. An example using the __call method follows.

The __call method of a class will be invoked when there is no method matching the method name that was called inside of the class. It will receive the method name, and an array of the arguments.

class OverloadTest {
    public function __call($method, $arguments) {
        if ($method == 'overloadedMethodName') {
            switch (count($arguments)) {
                case 0:
                    return $this->overloadedMethodNoArguments();
                    break;
                case 1:
                    return $this->overloadedMethodOneArgument($arguments[0]);
                    break;
                case 2:
                    return $this->overloadedMethodTwoArguments($arguments[0], $arguments[1]);
                    break;
            }
        }
    }

    protected function overloadedMethodNoArguments() { print "zero"; }
    protected function overloadedMethodOneArgument($one) { print "one"; }
    protected function overloadedMethodTwoArguments($one, $two) { print "two"; }
}

$test = new OverloadTest();
$test->overloadedMethodName();
$test->overloadedMethodName(1);
$test->overloadedMethodName(1, 2);

Alternatively, you can provide a function with default arguments which will effectively allow for syntax that looks like overloading. Such as:

function testFunction($one, $two = null, $three = null) {

}

testFunction(1);
testFunction(1, 2);
testFunction(1, 2, 3);

And, finally, as for the third method, you can of course always access the arguments as an array within the function itself

function variableFunction() {
    $arguments = func_get_args();

    switch (count($arguments)) {
       // ...
    }
}

variableFunction();
variableFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
Colin M
  • 13,010
  • 3
  • 38
  • 58