2

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 .();
}

?

1
  • 2
    The real question here is: Why do you have multiple functions that do the same thing? Commented Jun 5, 2011 at 22:06

4 Answers 4

7
for(i=0;i<10;i++){
  $method = 'getNum' . $i;
  echo  $test->$method();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alexs answer is correct. But the clean way is to create a method getNum() with an argument. Just sayin' ;)
2

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);
}

Comments

1

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}")); 
}

Comments

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

2 Comments

(Recommending) eval is evil ;)
There is nothing inherently wrong with this use of eval, even if it is not the optimal solution. Please check the mindless fearmongering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.