Php: creating functions in a for () loop

Does anyone know how I could write a function that could create other functions using the contents of a variable for that name?

Here is a basic example of what I am saying in php:

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

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

+3
source share
5 answers

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

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

I think the closest thing you can get in PHP is that it does not look like a general hack.

, . , . , - .

+6

create_function .

:

$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

: php.net

+2

PHP 5.3, lambdas:

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

$node7('hello');
+2
+1

?

Javascript :

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

, Node1, Node2,... Node9 .

-2

Source: https://habr.com/ru/post/1729438/


All Articles