Page 1 of 1

PHP5: Object function with multiple argument types

Posted: Sat Oct 23, 2004 1:59 am
by biglaz
With objects in php5 you can now require that an object-argument passed to a function be an instance of a specific class.

Code: Select all

function doStuff(Foo $f)
{
    echo $f->printStuff();
}
If $f is not an instance of Foo, something like this error occurs:
"Fatal error: Argument 1 must be an instance of foo"

But, is it possible to have multiple copies of the same function, but accepting different argument-types?

Code: Select all

function doStuff(Foo $f)
{
    echo $f->printStuff();
}

function doStuff(Bar $f)
{
    echo $f->deleteStuff();
}

function doStuff(Moo $f)
{
    echo $f->printOtherStuff();
}
I want to do different commands based on what type of object is passed, and I don't want to create different function names. I suppose I could just create if/else instanceof checks, but would something like the above be possible?

Thanks :)

Posted: Sat Oct 23, 2004 2:47 am
by rehfeld
maybe not defining the actuall function/method until you know what type of object is passed?

it would still involve if/else, but maybe its closer to what your trying to do....

are you sure this would not be better solved by just making/using distinct classes?

Posted: Sat Oct 23, 2004 2:51 am
by timvw
a workaround could be to come up with an interface..... this way, every class that implements that interface can have it's own implementation.. example:

Code: Select all

interface fooIF {
      public function doBar();
}

class imp1 implements fooIF {
     public function doBar() {
          echo "i'm imp1";
     }
}

class imp2 implements fooIF {
    public function doBar() {
          echo "i'm imp2";
    }
}


function handleBar(fooIF $imp)
      $imp->doBar();
}