Function Overloading and PHP
I’m proud of writing elegant code that can be easily read and intuitively understood. I use whitespace to increase my code’s readability, and I utilize simple, specialized programming language constructs to make my code more concise. For example, I’ll use PHP’s foreach construct, instead of a traditional for loop, to eliminate unnecessary indexers. This construct can also be found in Java, C#, Perl, as well as other programming languages. I also frequently use a PHP idiom, which I have never used in other languages, that allows for the convenient addition of elements into an array.
Because PHP features nonessential elements such as the array append operator, I am irked by PHP’s lack of a more useful feature: function overloading. The popular approach of appending a formal argument’s type to a function name is bothersome and inconvenient. The scheme begins to deteriorate source code aesthetics when the functions that require overloading accept more than one argument. Additionally, calling functionName($objectOfTypeA) and functionName($objectOfTypeB) is clearly more elegant than having to call functionNameTYPEA($objectOfTypeA) and functionNameTYPEB($objectOfTypeB). Function overloading would allow people to use a consistent interface, while allowing the implementation of a function to vary depending on the number and types of supplied arguments. Surely, there must be a way that type hints can be exploited to implement this much needed feature.
July 1st, 2008 at 4:21 pm
Wow, grats, you’re good at stating the obvious…
This article, for some reason, reminds me of the “I like turtles” kid…
July 7th, 2008 at 8:41 am
I find php’s handling of ‘overloading’ (in the sense that you use it) is very convenient. You can just use the if statement and determining the type of parameters to replicate the behaviour. However, if you want the integers and say only one string value also (eg ‘infinity’ or ‘any’) or to overload with a set (array) but keep all the functionality in one function, then php allows you to do this very easily. It is not a bug of php, it is a design choice. However, for safety critical software where you want very rigorous design and more easy bug checking, there are other languages available.
August 15th, 2008 at 11:24 am
Just found your website after a query on the same subject, and I’m beginning to accept that the only way of emulating such thing is:
/**
@brief does something
*/
function doSomething($param){
$type = gettype($param);
// do something according to type
switch($type){
default:
//by default, the original doSomething()
break;
}
}