简体   繁体   English

在PHP链中使用Variable作为方法来允许条件方法链

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

Is there a way to build the chain conditionally? 有条件建立链条的方法吗? Example: 例:

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

Then $filter is dynamic or conditionally set 然后$filter是动态的或有条件地设置

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

So if condition is met, the chain would become: 因此,如果满足条件,则链条将变为:

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

else 其他

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

Is this possible? 这可能吗? What is this called? 这个叫什么? Thank you 谢谢

Yes, through overloading with methods __get/__call, depending on if you need to pass arguments to the filter or not. 是的,通过方法__get / __ call的重载,取决于是否需要将参数传递给过滤器。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM