简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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