tags:

views:

95

answers:

5

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?

+2  A: 

You may want to use the create_function for that.

Example:

$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599

Example Source: php.net

Sarfraz
+1  A: 

You can create functions on the fly with create_function().

Björn
+7  A: 

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.

Pekka
This is necessary in PHP <=5.2.x. However, 5.3 offers a much cleaner solution.
Lucas Oman
A: 

Why would you want to do this?

Also in Javascript this is possible:

function nodefunctioncreator(){
  var o = {};
  for(var i = 1, i < 10, i++) {
    o["Node" + i] = function(){
      //code for each of the functions
    }
  }
  return o;
}

Calling the function with return an object containing functions Node1, Node2, ... Node9 doing well nothing.

svinto
+1  A: 

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');
Lucas Oman
+1 Hey, didn't know that!
Pekka