2

I would be glad to pass an extra variable that is created outside to the inner function in my custom module. That inner function is a hook. But i can not pass variable as an pareamter of that function, or could I ?

Nice to have ;) :

$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
echo $foo;
}

As a workaround, i can wrap $foo in a function and do i this way

function process_vars () {
    $foo = 1;
return $foo;
}

function hook_tapir_table_alter (&$table, $table_id )  {
    echo process_vars ();
}

How could i go without function call to outside function ? Any clues? Thanx!

1

You're already doing it the right way. You aren't in control of that particular hook so you can't control how it's invoked, and what parameters are passed.

Couple that with this information from the drupal_alter() docs:

A maximum of 2 alterable arguments is supported. In case more arguments need to be passed and alterable, modules provide additional variables assigned by reference in the last $context argument:

And that means that in order to make changes to the arguments you'll need to patch the module that provides the hook.

You might want to consider variable_get() and variable_set() if the $foo variable is likely to change at all, or DB storage if it's something major.

But using a helper function to return that data is perfectly good practice; there are dozens of examples of the same in Drupal core itself.

Or....you could use the global keyword (emphasis because I wouldn't personally recommend it, it's not particularly good practice to pollute the global scope).

That would go something like this:

$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
  global $foo;
  echo $foo;
}
|improve this answer|||||
  • 1
    Thanks, Clive, no it is nothing major and variable need not to change, it is only form alter to show additional info , calculations are done elswhere. But good that you brought additional info for other usages. Ill go with helper function, as it will be an array of some complexity, I will avoid global. – NenadP Jan 24 '13 at 16:57
  • At the end, i used variable_get and set, because $foo is being calculated in one hook, and it has been made available in other hook. I could not make any other method to work (helper function to share vars between two functions, use closures), and i was trying to avoid usng global or diving in oop. – NenadP Jan 26 '13 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.