使用变量作为 PHP 链中的方法以允许条件方法链接

use Variable as methods in PHP chain to allow conditional method chaining

有条件建链的方法吗?示例:

$chain = $restaurant->allFoods()->$filter->get();

那么$filter就是动态的或者有条件设置的

if ($user == "vegetarian")
{
    $filter = "->onlyVegetables()";
}

所以如果满足条件,链将变为:

$chain = $restaurant->allFoods()->onlyVegetables()->get();

其他

$chain = $restaurant->allFoods()->get();

这可能吗?这个叫什么?谢谢

是的,通过方法重载 __get/__call,取决于您是否需要将参数传递给过滤器。

<?php
function __get($user) {
  if($user == 'vegetarian') {
    return $this->onlyVegetables();
  }
  return $this;
}

http://php.net/manual/en/language.oop5.overloading.php