method overloading.

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm trying to find the best way to do method overloading in the least
hackish way.

First solution:
Using __call() and a switch (or two)

class MyClass {
  public __call( $method, $args ) {
    //maybe some code here to determine arg count and arg types with
    switch( $method ) {
      case "foo":
         //Another switch in here using arg count and types
      case "bar":
         //Another switch in here using arg count and types
      case default:
         //Throw an exception

$obj = new MyClass();

Second solution: Using default types

class MyClass {
  public function foo( $arg1=$something, $arg2=$another ) {
     // Do something

$obj = new MyClass();
$obj->foo();  // Fine because we have default args
$obj->foo( 1, 2 ); // Fine we are using different values
$obj->foo( null, 2 ); // Fine but passing null is ugly.. I don't like

What I was hoping for in the second solution would be explicitly pass
arg values ( Python-like ):

$obj->foo( $arg2 = 2 );  //This case we are using the default value
for arg1 but arg2 is overwritten.
I understand ( or so I think ) with in PHP would resolve to:
$obj->foo( 2 ); // Since $arg = 2 is evaluated then passed at the
first argument (arg1) arg2 is set to default

This may be a pipe dream but is there any way to do explicit passing
like Python in PHP? I can't seem to find anything in the docs so i'm
assuming there isn't.

Re: method overloading.

.oO(Derek Schrock)

Quoted text here. Click to load it

You could also play with a variable number of arguments, see
func_get_arg() etc.

Quoted text here. Click to load it

Nope. Skipping arguments like that is not allowed in PHP.

Another option (still ugly, though) might be to pass some or all
arguments as an associative array:

  public function foo(array $args) {

And then:

  $obj->foo(array('arg1' => 23, 'arg2' => 42));


Re: method overloading.

Quoted text here. Click to load it

Yeah, that was my third option.

Site Timeline