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
gettype()
switch( $method ) {
case "foo":
//Another switch in here using arg count and types
break;
case "bar":
//Another switch in here using arg count and types
break;
case default:
//Throw an exception
break;
}
}
$obj = new MyClass();
$obj->foo();
$obj->foo("str");
.....
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
this.
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.