1

I have been reading the documentation for module_load_include() and there's a warning that says:

Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.

Now I'm not sure what this "global context" means. I guess a page callback function is not in global context because I'd have to do a global $user to access the user entity. The only global context instance I can think of is in the index.php file at the root directory, but I don't think people normally code on this file because it'd be "hacking" Drupal core.

Am I just missing the whole concept of global context as used in Drupal?

2

It means the global scope, ie anything outside a function and namespace. It's the PHP 'global', not anything specific to drupal.

People tend to use module_load_include at the top of .module files to bring in includes, much like in a traditional standalone PHP project.

This is potentially bad because the required elements might not have been bootstrapped at that point, which can lead to errors; hence the warning not to use it in a global context.

1

In a global context means outside any function, method or class. If you were to use the following code, it would not give you the right result.

<?php

// Load the files containing the module code.
module_load_include('inc', 'mymodule', 'common.functions');

/*
 * Implements hook_node_load().
 */
function mymodule_node_load($nodes, $types) {
  // Decide whether any of $types are relevant to our purposes.
  if (count(array_intersect($types_we_want_to_process, $types))) {
    // Gather our extra data for each of these nodes.
    $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
    // Add our extra data to the node objects.
    foreach ($result as $record) {
      $nodes[$record->nid]->foo = $record->foo;
    }
  }
}

Instead, in that case, you should use require_once().

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.