在PHP链中使用变量作为方法以允许条件方法链接
有没有办法有条件地构建链?例如:在PHP链中使用变量作为方法以允许条件方法链接,php,function,methods,method-chaining,Php,Function,Methods,Method Chaining,有没有办法有条件地构建链?例如: $chain = $restaurant->allFoods()->$filter->get(); 然后,$filter是动态或有条件设置的 if ($user == "vegetarian") { $filter = "->onlyVegetables()"; } 因此,如果满足条件,该链将变为: $chain = $restaurant->allFoods()->onlyVegetables()->get
$chain = $restaurant->allFoods()->$filter->get();
然后,$filter
是动态或有条件设置的
if ($user == "vegetarian")
{
$filter = "->onlyVegetables()";
}
因此,如果满足条件,该链将变为:
$chain = $restaurant->allFoods()->onlyVegetables()->get();
否则
这可能吗?这叫什么?谢谢你是的,通过方法_get/_调用重载,这取决于你是否需要将参数传递给过滤器
<?php
function __get($user) {
if($user == 'vegetarian') {
return $this->onlyVegetables();
}
return $this;
}
你试过了吗?发生了什么?使用eval可以构建动态代码,但大多数人都说:“eval是邪恶的”如果我不能将\uuu get()
或\uu call()
附加到父模型中会怎么样?您可以扩展类或编写包装器来实现过滤器的外观方法。这取决于您尝试使用的类。
<?php
function __get($user) {
if($user == 'vegetarian') {
return $this->onlyVegetables();
}
return $this;
}