0

Is it possible to pass content that are not variables to a PHP function such as a loop or similar construct to be executed in the other function.

Here is a php version of how it can be done in javascript.

function myFunction($content){

    // something important that needs to be done before content

    $content

    // something important that needs to be done after content

}

myFunction({

    foreach($things_we_have as $key => $val){
        // Things to do in centre of the function
    }

});

Obviously that does not work. Can this be done and if so how?

Walrus
  • 19,801
  • 35
  • 121
  • 199

1 Answers1

1

You can use Closures/anonymous functions as the parameter of the function.

Example:

function myFunction($closure)
{

    // something important that needs to be done before content

    $closure($thingsWeHave);

    // something important that needs to be done after content

}

myFunction(function($thingsWeHave)
{
    foreach($thingsWeHave as $key => $val){
        // Things to do in center of the function
    }
});

Other examples are here and here

Random Dude
  • 872
  • 1
  • 9
  • 24
  • I'm an idiot. Would have needed to do that in JS as well. Forgot about the need to declare that it was a function inside the () – Walrus May 07 '20 at 16:30