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

这里的技术是共享的

You are here

在哪里声明一个全局变量 Where do I declare a global variable?

shiping1 的头像
I need to define a global variable. Where should I define it?
  1. I will not use the global variable in template files
  2. I should not use settings.php
  3. I will only use the global variable in all the custom module files


正确答案 Personally, I would either write module that abstracts away the need for a global variable, or at least has a getter function for retrieving it. Something like

function foo_get_the_service ()
{
  static $service;

  if (! isset($service)) {
    $service = foo_init_the_service();
  }

  return $service;
}

Several Drupal API functions do something similar (eg, menu_get_active_trail() andmenu_set_active_trail());

And then preferably, your module would also have helper functions so you don't need to access the global directly. If something really does need the global, then you would use the getter.

If your global is an instance of a proper PHP class, then you could look into using a real singleton.

shareimprove this answer
 

I think what you're looking for is making use of Drupal's variables using variable_set() to create it andvariable_get() to retrieve it for use in your modules.

To use variable_set() just provide the variable name and value: variable_set(name, value).

To use variable_get() you just need to provide the variable name and default value (to be used if not yet set): variable_get(name, default_value).

shareimprove this answer
 
3 
Just keep in mind that this is really meant for config type variables and not really meant for passing around stuff at runtime on normal pages. The reason is that variable_set() clears all caches, so this comes with a pretty significant performance hit. –  MPD Nov 9 '11 at 15:20
   
The variable_set() and variable_get() functions are made to set/get a persistent variable. The value will be stored in the database and shared by all requests (and all users). The question is not clear if this is a wanted feature. –  Pierre Buyle Nov 29 '11 at 20:49
来自  http://drupal.stackexchange.com/questions/15118/where-do-i-declare-a-global-variable
普通分类: