prady00
prady00

Reputation: 751

Defining a global variable inside module in Drupal

I am trying to save a global variable in my module and access it from another function. I don't want to store it in $_SESSION because I need this variable application wide. Following is the code what I am trying but it simply doesn't work.

  function popmeup_menu() {
    $items['example/feed'] = array(
    'title' => 'Example RSS feed',
     'page callback' => 'popmeup_page',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK
    );
    return $items;
  }

    function popmeup_page() {
      print variable_get($xmlt, "");
    }

    function popmeup_comment_insert($comment) {
      variable_set($xmlt,"xmltoreturn");
    }

Upvotes: 1

Views: 12619

Answers (3)

avpaderno
avpaderno

Reputation: 29699

popmeup_comment_insert()(an implementation of hook_comment_insert()) is called in a different page request than popmeup_page(). As consequence of this, any static or global variable is automatically reset when the relative page request is done.

The only alternative you have is using Drupal variables, or a custom database table used from your module. I would discard Drupal variables, as they are loaded during Drupal bootstrap, even if their value is not requested to build the page content. In your case, as you need those values when outputting your page, I would rather use a custom database table.

As you are using hook_comment_insert() to populate it, you should consider that different users can insert a new comment at the same time, or before your page callback is invoked. Your code should need to consider that. If two different users create a new comment, which value should be saved in the database?

Upvotes: 0

sbrattla
sbrattla

Reputation: 5386

If all you need is to have a place to store your variable WITHIN the same requests, for different functions to access, then have a look at drupal_static. If you need to keep track of your variable across multiple requests, then the $_SESSION is the place to look.

Mārtiņš Briedis is right about static_variables, and drupal_static is just the formalised way of doing it.

Upvotes: 4

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

To store a global variable, store it in $GLOBALS superglobal.

Or, perhaps, you can use a static value.

$GLOBALS: http://php.net/manual/en/reserved.variables.globals.php

static variables: http://php.net/manual/en/language.oop5.static.php

Upvotes: 5

Related Questions