Rounin
Rounin

Reputation: 29463

How can I create and execute a series of PHP Variable Functions in a for loop?

I'm unfamilar with using variable functions in PHP, but I've repeatedly re-read the manual:

and it's not at all clear what I'm doing wrong here:

for ($i = 0; $i < 10000; $i++) {

  $Function_Name = 'Test_Function_'.sprintf('%03d', $i);

  function $Function_Name() {

    echo  __FUNCTION__.' is working.';
  }

  $Function_Name();
}

Why is this loop not creating and running 10000 variable functions?


Alternative using anonymous functions

An alternative approach (using anonymous functions) doesn't seem to work either:

for ($i = 0; $i < 10000; $i++) {

  $Function_Name = 'Test_Function_'.sprintf('%03d', $i);

  ${$Function_Name} = function () {

    echo  __FUNCTION__.' is working.';
  }

  ${$Function_Name}();
}

Upvotes: 1

Views: 59

Answers (1)

Stefanov.sm
Stefanov.sm

Reputation: 13049

Please note that anonymous (lambda) functions only see (closure) variables from the external scope if they are explicitly listed with "use" i.e.

${$Function_Name} = function () use ($Function_Name)

and then it works as expected.

for ($i = 0; $i < 10000; $i++) 
{    
  $Function_Name = 'Test_Function_'.sprintf('%03d', $i);
  ${$Function_Name} = function () use ($Function_Name)
  {
    echo  $Function_Name.' is working.'.PHP_EOL;
  };
  ${$Function_Name}();
}

Upvotes: 1

Related Questions