开发者

calling function - variables

i have:

  echo  $test->getNum1();
  echo  $test->getNum2();
  echo  $test->getNum9();

how can i make开发者_运维问答 something:

for(i=0;i<10;i++){
  echo  $test->getNum . $i .();
}

?


for(i=0;i<10;i++){
  $method = 'getNum' . $i;
  echo  $test->$method();
}


As a complement to Alex's answer, you can also specify a variable name for a function by using call_user_func or call_user_func_array. These take a callback as their first argument, so you can provide a string within this. In this case you could do something like the following:

for($i=0; $i<10; $i++){
  $method = array($test, 'getNum' . $i);
  echo call_user_func($method);
}


This one will be simplest and most robust (that is if you don't want to write 5 more lines with the reflection api):

for($i=0; $i<10; $i++) {
  echo call_user_func(array($test, "getNum{$i}")); 
}


for ($i = 0; $i < 10; $i++) {
    echo eval('$text->getNum'.$i.'()');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜