Is there a way to call a function from my module that is located in another module? I thought that I read somewhere you can do this, but I can't seem to find where that is done. I am trying to call a function from ubercart.

Comments

AjK’s picture

Calling a function from module to another is simply a matter of calling the function just like any other. However, be awares that if the module is not enabled you'll throw a PHP error. To avoid this wrap any calls going out inside of a test like this:-

  if (module_exists('module_name')) { 
    module_name_function_name();
  }

if you are truely paranoid you could do this also:-

  if (module_exists('module_name') && function_exists('module_name_function_name')) { 
    module_name_function_name();
  }

or simply

  if (function_exists('module_name_function_name')) { 
    module_name_function_name();
  }

The module_exists() function is a Drupal API call that tells you if a module is enabled. function_exists() is a PHP function that tells you if the function is defined and available to you.

Of course, if the other module is not enabled you should handle accordingly. But there exists a method in teh .info file to specify dependancy on other modules.

johnmurray’s picture

If you are calling a function from another module in your module code, and your code depends on that function, then it is safe to say that you could declare the module as a dependency in your .info file to ensure (somewhat) that the module is installed. Just thinking that this might make it a little more safe.

however, you would still wan to check for the existence of the function. (in case the next module version doesn't include it)

jiv_e’s picture

You can also consider using module_invoke function.

Function definition in a module:
function MYMODULE_function_name(...)

Function call in another module:
module_invoke('MYMODULE', 'function_name', arg1, arg2,...)

Jaypan’s picture

Note that that is for calling hooks.

Also note that you can call any function that is in any module's .module file, but if it is in a different file, you'll first need to include the file using module_load_include().