Tuesday, February 17, 2009

Call a function from another module

Call a function from another module

j_ten_man - February 7, 2008 - 23:43

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.

Calling a function from

AjK - February 8, 2008 - 01:30

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:-

<?php
if (module_exists('module_name')) {
module_name_function_name();
}
?>

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

<?php
if (module_exists('module_name') && function_exists('module_name_function_name')) {
module_name_function_name();
}
?>

or simply

<?php
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.

No comments: