Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By j_ten_man on
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
Calling a function from
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 you are truely paranoid you could do this also:-
or simply
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.
Dependency
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)
Using module_invoke
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,...)
Note that that is for calling
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().