1

I have some code like this

$form_names = GFFormsModel::get_forms();
foreach ($form_names as $form) {
  add_action("gform_pre_submission_".$form->id, "format_ecp_event_meta_from_gravity");

  function format_ecp_event_meta_from_gravity(){

  }
}

Since i'm using foreach loop functions get duplicated. So is there a way to make the function unique using $form->id ?

I mean i want the function names like this

function format_ecp_event_meta_from_gravity_{$form->id}(){

}

Can someone help me? Thanks

4
  • Looks like the perfect use case scenario for an anonymous function: php.net/manual/en/functions.anonymous.php Commented Jul 7, 2013 at 11:12
  • can you explane what you want to do with this functions i think it's not good to create functions on loop Commented Jul 7, 2013 at 11:14
  • @Niko But my function has very large code. CAn you explain how to use large code in anonymous function? Commented Jul 7, 2013 at 11:45
  • @Giri It's just the same as with normal functions. Just the first line is different. Commented Jul 7, 2013 at 11:52

1 Answer 1

2

Use closures:

$form_names = GFFormsModel::get_forms();
foreach ($form_names as $form) {
    $func = function() {
        ...
    };
    add_action("gform_pre_submission_".$form->id, $func);
}
Sign up to request clarification or add additional context in comments.

5 Comments

The functions probably also need to be passed into add_action() because they seem to get invoked there.
@hek2mgl Could you explain this last line $functions ['func_name']= $func; ? what name should i replace with func_name?
@Giri Note that your question is really vague because I don't know what add_action does. (You missed to describe that properly in your question). But without knowing more I would suggest to simply drop that last line. check my update
add_action is a wordpress hook. Hey is it possible to change $func variable to ${'func_'.$form->id} ?
@Giri You should give this a try! Wordpress probably uses call_user_func_array to invoke the function and that should also work with a closure.

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.