Function Overloading in PHP
Well… not quite.
This might be an old, tired, boring hack to some, but it’s new to me. I had a function – call it f()… my math background won’t leave me alone – and I needed it to take several forms. In one place, I wanted to pass in a single value, and in another place, I wanted f() to operate on an array of such values. But PHP does not support function overloading because it’s not cool enough.* After a bit of thought, I came up with a pretty sane way of having the cake and eating it, too.
public function f( $x ) { if ( !is_array( $x ) ) { $x = array( $x ); } foreach ( $x as $item ) { // Do your work on each element } return; }
Cheers!
*This is actually an artifact of the extreme flexibility of the language. Because of PHP’s loose, dynamic typing, there isn’t a sane way for PHP to be able to tell the difference between a call to go( $a ) where $a holds an integer and go( $b ) where $b holds a string (read: there isn’t a compelling enough excuse for anyone to waste their time implementing such a feature).
I do this all the time in PHP. Often I have a method that say updates a MySQL table. You can pass it an array to update multiple values, or pass it a single string to update just that field.
Also useful on class constructors. Did you pass an integer? Okay, I’ll assume that’s the id and look it up in a table. Did you pass a string? Okay, I’ll just use that data to create the object.
It’s a little janky, but if you comment well…