如何缩短此PHP代码以使其更通用


How do I shorten this PHP code to be more general?

对于阅读过这篇文章的PHP大师,我相信你会理解我在这里寻找的东西。我正在寻找一种通用的方法来做我已经在做的事情。目前,我支持一个方法值,它最多有6个用|字符分隔的方法名。如果我想支持n个方法,其中n可以是任何数字,我该如何转换下面的代码。我基本上是在寻找有助于减少我目前拥有的代码量的语法。

// example value for $method 
// $method = 'getProjectObject|getProgramObject|getName';
$methods = explode('|', $method);
if (sizeof($methods) == 1) {
    $value = $object->$method();
}
else if (sizeof($methods) == 2) {
    $value = $object->$methods[0]()->$methods[1]();
}
else if (sizeof($methods) == 3) {
    $value = $object->$methods[0]()->$methods[1]()->$methods[2]();
}
else if (sizeof($methods) == 4) {
    $value = $object->$methods[0]()->$methods[1]()->$methods[2]()->$methods[3]();
}
else if (sizeof($methods) == 5) {
    $value = $object->$methods[0]()->$methods[1]()->$methods[2]()->$methods[3]()->$methods[4]();
}
else if (sizeof($methods) == 6) {
    $value = $object->$methods[0]()->$methods[1]()->$methods[2]()->$methods[3]()->$methods[4]()->$methods[5]();
}
$methods = explode('|', $method);
$ret = $object;
foreach ($methods as $method)
{
    $ret = $ret->$method();
}
return $ret;

您可以使用类似foreach:的循环

$methods = explode('|', $method);
foreach ($methods as $method) {
    $object = $object->$method();
}
$value = $object;