Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.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_Function_Methods_Method Chaining - Fatal编程技术网

在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;
}