Alex
Alex

Reputation: 10226

Drupal how to pass variable to file using module_load_include?

I have a function within my module:

<?php
function foo($node) {
module_load_include('php', 'mymodule', 'path/to/filename');
}
?>

in filename.php i would like to be able to access the $node variable, or any other.

<?php
var_dump($node);
?>

how can i achieve that resp. how do you do this?

Upvotes: 0

Views: 757

Answers (1)

theunraveler
theunraveler

Reputation: 3284

No, there is no way to do this using module_load_include(). From php.net:

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

Since the include happens inside module_load_include(), the include file will contain all variables that are in the scope of that function, not your function.

You can either:

  1. Add a function your include file, then call that function inside your foo() function after using module_load_include().
  2. Use a regular PHP include instead of module_load_include(): include DRUPAL_ROOT . '/' . drupal_get_path('module', 'mymodule') . '/path/to/filename.php';

Also, a word of advice: it is generally a bad idea to not wrap functionality in functions. When you use functions, you get better variable scoping, fewer unintentional side effects, and better code reusability. So, I would suggest you choose the first option.

Upvotes: 2

Related Questions