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

故事扮演 提交于 2019-12-13 15:25:57

问题


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!


回答1:


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.




回答2:


$lunch->{'order_' . $myOrder}();

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




回答3:


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.




回答4:


simple enough

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


来源:https://stackoverflow.com/questions/936875/how-would-i-call-a-method-from-a-class-with-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!