Simulating method overloading

Nov 25, 2010 Author: GDchart-Master

One neat trick offered by some OOP languages (and not offered by PHP) is automatic overloading of member functions. This means that you can define several different member functions with the same name but different signatures (number and types of arguments). The language itself takes care of matching up calls to those functions with the right version of the function, based on the arguments that are given.

PHP does not offer such a capability, but the loose typing of PHP lets you take care of one half of the overloading equation — you can define a single function of a given name that behaves differently based on the number and types of arguments it is called with. The result looks like an overloaded function to the caller (but not to the definer). Here’s an example of an apparently overloaded constructor function:

class MyClass
{
public $string_var = “default string”;
public $num_var = 42;
public function __construct($arg1) {
if (is_string($arg1)) {
$this->string_var = $arg1;
}
elseif (is_int($arg1) ||
is_double($arg1)) {
$this->num_var = $arg1;
}
}
}
$instance1 = new MyClass(“new string”);
$instance2 = new MyClass(5);

The constructor of this class will look to its caller as though it is overloaded, with different behavior based on the type of its inputs. You can also vary behavior based on the number of arguments by testing the number of arguments supplied by the caller.

tags:

views 5216
  1. Add New Comment