views:

203

answers:

3

I'd like to accomplish something like this: Call a method, say "turn", and then have "turn" applied differently to different data types, e.g., calling "turn" with a "screwdriver" object/param uses the "turnScrewdriver" method, calling "turn" with a "steeringWheel" object/param uses the "turnSteeringWheel" method, etc. -- different things are being done, but they're both called "turn."

I'd like to implement this so that the calling code needn't worry about the type(s) involved. In this example, "turn" should suffice to "turn" a "screwdriver", "steeringWheel", or whatever might need to be "turned."

In C++ I'd do this with overloading -- and C++ would sort things out based on the datatype/signature -- but this doesn't work in PHP.

Any suggestions as to where should I begin? A switch statement is obvious, but I'm thinking there must be a (more elegant) OO solution. No?

TIA

A: 

You need to check the PHP Manual for instructions here

Filip Ekberg
+2  A: 

I think this will work...

function turn($object) {
    if(method_exists($object, 'turn'.ucwords(get_class($object))) {
        $fname = 'turn'.ucwords(get_class($object));
        return $object->$fname();
    }

    return false;
}
davethegr8
+8  A: 

I read davethegr8's solution but it seems one could do the same thing with stronger typing:

<?php

interface Turnable
{
  public function turn();
}

class Screwdriver implements Turnable
{
  public function turn() {
    print "to turning sir!\n";
  }
}

class SteeringWheel implements Turnable
{
  public function turn() {
    print "to everything, turn, turn turn!\n";
  }
}

function turn(Turnable $object) {
  $object->turn();
}

$driver = new Screwdriver();
turn($driver);

$wheel = new SteeringWheel();
turn($wheel);

$obj = new Object(); // any object that does not implement Turnable
turn($object); // ERROR!

PHP does permit you to use a type hint for the parameter, and the type hint can be an interface name instead of a class name. So you can be sure that if the $object implements the Turnable interface, then it must have the turn() method. Each class that implements Turnable can do its own thing to accomplish turning.

Bill Karwin
Very nice that. My immediate thought was interface inheritance, but I left the PHP world before learning OOP.
ck
Nice turn of phase sir! And well put. +1
meouw