Vamsi Krishna B Vamsi Krishna B - 2 years ago 158
PHP Question

PHP function overloading

Coming from C++ background ;)

How can I overload PHP functions?

One function definition if there are any arguments, and another if there are no arguments?
Is it possible in PHP? Or should I use if else to check if there are any parameters passed from $_GET and POST?? and relate them?

Answer Source

You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

For example:

function myFunc() {
    for ($i = 0; $i < func_num_args(); $i++) {
        printf("Argument %d: %s\n", $i, func_get_arg($i));

Argument 0: a
Argument 1: 2
Argument 2: 3.5
myFunc('a', 2, 3.5);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download