-1

For the PHP masters who read this, I'm sure you'll understand what I'm looking for here. I'm looking for a general way to do what I'm already doing. Currently, I support a method value that has up to 6 method names separated by a | character. If I wanted to be able to support n methods where n could be any number, how could I convert the code below. I'm basically looking for syntax that will help decrease the amount of code I currently have.

// 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]();
}
4

2 に答える 2

3

次のようなループを使用できますforeach

$methods = explode('|', $method);
foreach ($methods as $method) {
    $object = $object->$method();
}
$value = $object;
于 2013-02-06T18:53:34.097 に答える
3
$methods = explode('|', $method);
$ret = $object;
foreach ($methods as $method)
{
    $ret = $ret->$method();
}
return $ret;
于 2013-02-06T18:54:36.353 に答える