1

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}();
}
5
  • What are you trying to achieve here? I see no possible way this could actually be useful. Commented Jun 6, 2020 at 11:39
  • I am setting up a speed test. Creating and running 10,000 functions will give me the baseline. Then I will compare against creating and including 10,000 files containing functions. Then I will compare against creating and eval()-ing 10,000 strings. Commented Jun 6, 2020 at 11:41
  • you cannot define a function with a variable. You must use the name of the variable function Function_Name() { Commented Jun 6, 2020 at 11:42
  • You could just use anonymous functions. $some_function = function() { /* do stuff */ } and then call $some_function(); Commented Jun 6, 2020 at 11:42
  • Thanks, @NiettheDarkAbsol. Before I posted I did attempt an alternative approach using anonymous functions (now added to the question above) but I couldn't make that work, either. Commented Jun 6, 2020 at 11:49

1 Answer 1

1

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}();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant work, Stefanov.sm. @NiettheDarkAbsol was also right that I should use an anonymous function, which I'd tried, but what I'd missed in my own test (and still visible in my question at the top) is that I had failed to demarcate the end of the assignment with a ;. Your tip regarding use is very helpful. Thank you.
More on deploying use in this context here: blog.dubbelboer.com/2012/04/07/php-use-keyword.html

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.