欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

定义全局变量 Defining a global variable inside module in Drupal

shiping1 的头像
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 desn't works.
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");}



正确答案 To store a global variable, store it in $GLOBALS superglobal.

Or, perhaps, you can use a static value.

$GLOBALShttp://php.net/manual/en/reserved.variables.globals.php

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

shareimprove this answer
 
   
Actually, popmeup_page(), and popmeup_comment_instert() are called in two different page requests. This means that any global, or static variable is reset, and the value passed to those variables is not kept. – kiamlaluno Jan 2 '13 at 15:53

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.

shareimprove this answer
 
   
This is the correct answer, as it considers when the value is required inside the same page request, or in different requests. –  kiamlaluno Jan 2 '13 at 16:14

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?

来自  http://stackoverflow.com/questions/12559540/defining-a-global-variable-inside-module-in-drupal
普通分类: