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
I read davethegr8’s solution but it seems one could do the same thing with stronger typing:
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
$objectimplements theTurnableinterface, then it must have theturn()method. Each class that implementsTurnablecan do its own thing to accomplish turning.