Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php: creating functions in a for () loop

Tags:

c

php

Does anybody know how I could write a function, that was able to create other functions, using the contents of a variable for it's name?

Here's a basic example of what I'm talking about in php:

function nodefunctioncreator()
  {
    for ($i =1, $i < 10, $i++)
      {
      $newfunctionname = "Node".$i;
      function $newfunctionname()
        {
        //code for each of the functions
        }
      }
  }

Does anybody know a language that would allow me to do this?

like image 670
JoeCortopassi Avatar asked Jan 22 '23 17:01

JoeCortopassi


2 Answers

You can create anonymous functions in PHP using create_function(). You could assign each anonymous function to a variable $newfunctionname and execute it using call_user_func():

$newfunctionname = "Node".$i;
$$newfunctionname = create_function('$input', 'echo $input;'); 
// Creates variables named Node1, Node2, Node3..... containing the function

I think that's the closest you can get in PHP in a way that doesn't look like a total hack.

I don't think it's possible to define a function directly from a variable. It wouldn't look good to me to do it, either, because you would be polluting the namespace with those functions. If anonymous functions don't work, this calls for an object oriented approach.

like image 131
Pekka Avatar answered Feb 01 '23 11:02

Pekka


If you're using PHP 5.3, you can use lambdas:

for ($i=0;$i<10;$i++) {
  $funcName = 'node'.$i;
  $$funcName = function ($something) {
    // do something
  }
}

$node7('hello');
like image 44
Lucas Oman Avatar answered Feb 01 '23 10:02

Lucas Oman