PHP5: Object function with multiple argument types

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
biglaz
Forum Newbie
Posts: 5
Joined: Fri Oct 22, 2004 8:53 pm

PHP5: Object function with multiple argument types

Post 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 :)
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post 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?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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();
}
Post Reply