0

Is possible to make for loop function for php, that works like this

function hit(){

}

function forLoop($function, $times) {

for($x = 0; $x < $times; $x++) {
    $function;
}

$this->forLoop($function, 5);
5
  • 2
    For sure! Just try it out. (Typo 1: forgot 1 closing curly bracket for the forLoop function Typo 2: parentheses for the function call: $function();) Commented Feb 18, 2015 at 8:33
  • possible duplicate of Use Variable as Function Name in PHP Commented Feb 18, 2015 at 8:35
  • Could I do $this->forLoop($this->getScore, 5); Commented Feb 18, 2015 at 8:40
  • If your code is in a class context e.g. class declaration and $this->getScore Is holding a name for a function sure why not? Commented Feb 18, 2015 at 8:41
  • can I do $this->getScore($something), 5 Commented Feb 18, 2015 at 9:33

1 Answer 1

0

This can be done with the call_user_func function:

function hit(){
    echo "hello !";
}

function forLoop($function, $times) {

    for($x = 0; $x < $times; $x++) {
        call_user_func($function);
    }
}

forLoop('hit', 5);
Sign up to request clarification or add additional context in comments.

2 Comments

You also can simply write: $function();
for ($hole = 0; $hole < 18; $hole++) { $function; } public function generateCourse($course, $type) { $this->runFunction($this->generateHole($hole), $type); }

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.