Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从带有变量的类调用方法?_Php_Oop_Variable Variables - Fatal编程技术网

Php 如何从带有变量的类调用方法?

Php 如何从带有变量的类调用方法?,php,oop,variable-variables,Php,Oop,Variable Variables,鉴于这一类别: 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(); $lunc

鉴于这一类别:

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;
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";
        }
    }
}
很明显,这段代码是胡说八道——但它显示了我试图做得比试图解释它更好

也许我在这件事上做错了。我考虑了一个带有switch语句的方法,传入玉米煎饼或玉米卷,然后从那里调用正确的方法。但是我必须从一开始就知道结束,我可能有很多方法,我不希望每次都更新switch语句

谢谢

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

我确实同意设计有点不确定,但至少是这样做的。

我认为
呼叫用户功能
是您想要的:


你可以把你建议的字符串传给它。有关调用类的方法,请参见示例#3。

类似的内容如何

$myOrder = 'burrito';
$lunch->order_.$myOrder;
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";
        }
    }
}
您可以使用$午餐->订单('burrito');,对我来说这看起来干净多了。它让Tacobell::order方法变得丑陋不堪。

足够简单

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

这可以使用对象来完成,您可以为每个项创建类,每个类都可以符合相同的接口,然后使用一个order()方法来获取OrderItem对象,该对象可以是BurritoOrderItem或TacoOrderItem。当需要反射或者有变量方法调用时,我总是畏缩,这对我来说就是不干净。到目前为止,所有的答案都是我需要的,但这就是我一直在寻找的。谢谢大家。我仍然不确定这是我想要的方式,但是现在它从我的代码中得到了最大的重用。