Jump to content

Using loop to output a set of functions


nicholas.alipaz

Recommended Posts

I am working on a project that hooks into the api provided by another project.  The main api requires that I provide a function for each instance of a hook.

 

Example:

function my_function_0() {
  //do some stuff
}
function my_function_1() {
  //do some stuff again
}
//etc...

What I would like to do is to generate these functions instead of rewriting them.  All the functions will do the same thing with just some alternate variables, but the other project I am hooking into requires that each one be there.

 

How could I do something like:

  $result = db_query("SELECT * FROM mytable WHERE lid = %d", $lid);
  $row = null;
  $row = db_fetch_array($result);
  while ($row) {
    function my_function_{$row['lid']} {
      //do some stuff
    }
  }

Obviously the above doesn't work, but how would I go about doing something similar. 

 

Alternatively, could I somehow do something like:

  $result = db_query("SELECT * FROM mytable WHERE lid = %d", $lid);
  $row = null;
  $row = db_fetch_array($result);
  while ($row) {
    $my_function_{$row['lid']} = my_function_default();
  }

If any of this is possible, please help me with the right syntax.  I am a little lost.  Thanks.

Link to comment
https://forums.phpfreaks.com/topic/191509-using-loop-to-output-a-set-of-functions/
Share on other sites

u can not create a bunch of function i a loop...

but u can create a loop thats write thoose functions to empty php file...

 

not quite true. you can use eval if you wanted to, or, probably the better choice, create_function()

 

anonymous functions would probably also work for you

Thanks for the tip mikesta707.

 

I got it with this:

  $result = db_query("SELECT * FROM mytable WHERE lid = %d", $lid);
  $row = null;
  $row = db_fetch_array($result);
  while ($row) {
    $id = 'my_function_'. $row['lid'];
    $lid = $row['lid'];
    // here we create a function as a variable to be reused
    $my_function_default = sprintf('
    function %s($op, &$arg1, $arg2) {
      // do some stuff
      return %s;
    }', $id, $lid);
    // initialize this function, YAY!
    eval($my_function_default);
  }

Now this was fun and something for the books for sure!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.