如何从具有变量的类中调用方法? [英] How would I call a method from a class with a variable?
问题描述
提供此类:
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();
我该怎么做?
$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.
也许我正在解决所有这些错误.我考虑过一个带有switch语句的方法,传入burrito或taco,然后从那里调用正确的方法.但是然后我必须从一开始就知道结束,我可能有很多方法,而我宁愿不必每次都更新switch语句.
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.
谢谢!
推荐答案
这样的事情怎么样?
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";
}
}
}
您可以使用$ lunch-> order('burrito');来调用它,它对我来说看起来更干净.它把所有的丑陋都放在了Tacobell :: order方法中.
You would call it using $lunch->order('burrito');, which looks much cleaner to me. It puts all the uglyness in the method Tacobell::order.
这篇关于如何从具有变量的类中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!