Php – Why PHP doesn’t support function overloading

method-overloadingPHP

I am wondering if one of the key features of a programming language is to have the ability to overload functions via arguments. I think it is essential in-context of the Object oriented programming.

Is it intentionally left behind and not allowed? Or is overloading not a good practice?

Best Answer

Not a "Traditional Overloading" full support, only partial.

A DEFINITION: "Traditional Overloading" provides, when calling method, the ability to have multiple methods with the same name but different quantities and types of arguments. For method declaration, it provides the option to express a separate/isolated declaration for each overloaded function.

Note: the second part of this definition is usually associated with statically-typed programming languages which do type checking and/or arity checking, to choose the correct declaration. PHP is not a statically-typed language, it is dynamic, and use weak typing.


PHP SUPPORT:

  • YES, provides the ability to call multiple methods with the same name but different quantities. See func_get_args and @rajukoyilandy answer, we can use f(x) and f(x,y).

  • YES, provides the ability to call multiple methods with the same name but different types. Se internal use of gettype in the method.

    • BUT for references... Only variables can be passed by reference, you can not manage a overloading for constant/variable detection.
  • NOT provides the ability to declare multiple methods with the same name but different quantities. This is because we can call f(x) and f(x,y) with the same f declaration.

  • NOT provides the ability to declare multiple methods with the same name but different types. This is because PHP compiler must interpret f($integer,$string) as the same function that f($string,$integer).

See also PHP5 overloading documentation for the "non-traditional overloading" explanations.

Related Topic