views:

105

answers:

4

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!

+2  A: 
$lunch->{'order_' . $myOrder}();

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

Paolo Bergantino
+2  A: 

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.

kristina
+4  A: 

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
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.
rpflo
A: 

simple enough

$order = 'order_burrito';
$lunch->$order();
Ozzy