Something like overloading in PHP?

I would like to accomplish something like this: call the method, say “rotate”, and then “rotate” as applied differently to different types of data, for example, call the “rotate” using the screwdriver / param object uses the “turnScrewdriver method ", causing a" turn "using the" steering wheel "of the object / param, uses the method" turnSteeringWheel ", etc. - Different things are done, but both of them are called "turn".

I would like to implement this so that the calling code does not worry about type (s). In this example, the “turn” should be sufficient to “turn” the “screwdriver”, “steering wheel”, or any other that can be “turned”.

In C ++, I would do this with overloading - and C ++ would sort things based on data / signature type, but this does not work in PHP.

Any suggestions on where to start? The switch statement is obvious, but I think there should be a (more elegant) OO solution. No?

TIA

+3
source share
3 answers

I am reading a davethegr8 solution, but it seems like you could do the same with a more strict type:

<?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 , . , $object Turnable, turn(). , Turnable, , .

+8

, ...

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

    return false;
}
+2

You need to check the PHP manual for instructions here.

0
source

Source: https://habr.com/ru/post/1702212/


All Articles