有条件地链接方法?

Loo*_*arn 6 php oop

我们如何有条件地在PHP中链接方法?例如,这可以正常工作:

$a->foo()->bar->baz->qux();
Run Code Online (Sandbox Code Playgroud)

但是,根据条件,我想链接一些方法,但不链接其他方法。基本上,缩短以下代码:

if ($cond === true) {
    $a->foo()->baz();
} else {
    $a->foo()->bar();
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,类似以下内容的方法将起作用:

$a->foo()
    ->bar()
    ($cond === true) ? ->baz() : ->qux()
    ->more();
Run Code Online (Sandbox Code Playgroud)

另外,我们如何根据条件有条件地链接一个方法(或不链接)?例如:

$a->foo()
    ->bar()
    if($cond === true) ->baz()
    ->more();
Run Code Online (Sandbox Code Playgroud)

Kev*_*ich 2

您正在寻找的是可变方法(参见示例#2)。它们允许你做这样的事情:

class a {
    function foo() { echo '1'; return $this; }
    function bar() { echo '2'; return $this; }
    function baz() { echo '3'; return $this; }
}
$a = new a();

$cond = true;
$a->foo()->{($cond === true) ? 'baz' : 'bar'}();
// Prints 13
$cond = false;
$a->foo()->{($cond === true) ? 'baz' : 'bar'}();
// Prints 12
Run Code Online (Sandbox Code Playgroud)

这是一种可以让您为每个函数调用设置要求的方法。请注意,这与之前的解决方案一样难以维护,甚至更难。您可能还想使用某种配置和ReflectionClass's getMethods function

class a {
    function foo() { echo '1'; return $this; }
    function bar() { echo '2'; return $this; }
    function baz() { echo '3'; return $this; }
}

function evaluateFunctionRequirements($object, $functionRequirements, $condition) {
  foreach ($functionRequirements as $function=>$requirements) {
    foreach ($requirements as $requiredVariableName=>$requiredValue) {
      if (${$requiredVariableName} !== $requiredValue) {
        continue 2;
      }
    }
    $object->{$function}();
  }
}

$a = new a();
$functionRequirements = array('foo'=>array(), 'bar'=>array(), 'baz'=>array('condition'=>true));
$condition = true;
evaluateFunctionRequirements($a, $functionRequirements, $condition);
// Prints 123
$condition = false;
evaluateFunctionRequirements($a, $functionRequirements, $condition);
// Prints 12
Run Code Online (Sandbox Code Playgroud)

注意:这使得维护数组的功能变得更加困难$functionRequirements。此外,这个基本示例仅传递了一个可能的条件 var,请更新到另一设置以使用func_get_args获取更多 $requiredVariableName var 。您还需要验证通过 $functionRequirements 传入的方法是否is_callable()安全。