0

Basically, I am looking for a way I could optimize the following. Not really a PHP programmer, and in the Ruby world this would be easy, but at the moment I have this:

if(count($methods) == 1) {
    $resp = $this->$methods[0];
}
else if(count($methods) > 1) {
    $resp = $this->$methods[0]->$methods[1];
}

Is there somehow a way I could loop over the methods array here, and chain them together?

Thanks!

TheApeMachine
  • 59
  • 1
  • 5

1 Answers1

0

What you want is essentially an array reduction:

$resp = array_reduce($methods, function ($o, $p) { return $o->$p; }, $this);

It's unclear whether you want $o->$p (property access) or $o->$p() (method call), but you can figure that out.

deceze
  • 510,633
  • 85
  • 743
  • 889