2

Given this class:

class Tacobell{

    public function order_taco(){
        echo "3 Tacos, thank you.";
    }

    public function order_burrito(){
        echo "Cheesy bean and rice, please";
    }

}

$lunch = new Tacobell;
$lunch->order_burrito();
$lunch->order_taco();

How would I do something like this?

$myOrder = 'burrito';
$lunch->order_.$myOrder;

Obviously that code is bunk--but shows what I'm attempting to do better than trying to explain it away.

And maybe I'm going about this all wrong. I thought about a method with a switch statement, pass in burrito or taco, then call the right method from there. But then I have to know the end from the beginning, and I may potentially have lots of methods and I'd rather not have to update the switch statement everytime.

Thanks!

Ryan Florence
  • 13,361
  • 9
  • 46
  • 63
  • 1
    This could be done using objects, you can have classes for each item, each can conform to the same interface, then have a single order() method that will take a OrderItem object which could either be a BurritoOrderItem or a TacoOrderItem. I always cringe when Reflection is needed or when you have variable method calls, it just isn't clean to me. – Kekoa Jun 01 '09 at 21:33

4 Answers4

5

How about something like this?

class Tacobell {
    public function order_burrito() {
         echo "Bladibla.\n";
    }

    public function order($item) {
        if (method_exists($this, "order_$item")) {
            $this->{'order_' . $item}();
        } else {
            echo "Go away, we don't serve $item here.\n";
        }
    }
}

You would call it using $lunch->order('burrito');, which looks much cleaner to me. It puts all the uglyness in the method Tacobell::order.

rodion
  • 6,087
  • 4
  • 24
  • 29
  • All the answers so far have been what I needed, but this what I was looking for. Thanks all. I'm still not sure this is how I want to do it though, but for now it gets the most reuse out of my code. – Ryan Florence Jun 01 '09 at 23:30
3
$lunch->{'order_' . $myOrder}();

I do agree the design is a little iffy, but that's how to do it at least.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
2

I think call_user_func is what you're looking for:

http://us3.php.net/call_user_func

You can pass it the string you suggested. See example #3 for calling a method of a class.

kris
  • 23,024
  • 10
  • 70
  • 79
0

simple enough

$order = 'order_burrito';
$lunch->$order();
Ozzy
  • 10,285
  • 26
  • 94
  • 138