我可以以某种方式在 PHP 中链接方法吗?



基本上,我正在寻找一种可以优化以下内容的方法。 不是真正的PHP程序员,在Ruby世界中这很容易,但目前我有这个:

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

有没有办法在这里循环方法数组,并将它们链接在一起?

谢谢!

你想要的本质上是一个数组缩减:

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

目前还不清楚您是想要$o->$p(属性访问(还是$o->$p()(方法调用(,但您可以弄清楚。