Search code examples
phpoopvariable-variables

How would I call a method from a class with a variable?


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!


Solution

  • 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.