I have a very stupid question, but I can't find anywhere the answer :)
I want to create a new object in my module like $user wich can be called from any module just when putting global $myobject; This variable must be declared once when user logs.
I am waiting for your help


jjeff’s picture

If you want a global variable declared by your module and available to other modules then you would use the basic PHP functions for declaring a variable as global: http://us2.php.net/global

And you would probably do it from within hook_menu() because this happens very early on in the life cycle of a page load, so your code would look something like this:

function mymodule_menu($may_cache){
    // put any menu items that can be cached here
  else {
    global $my_variable;
    global $user;
    $my_variable = db_fetch_object(db_query('SELECT FROM {foo} WHERE uid = %d', $user->uid));

However depending on what you're doing, it may be better to use Drupal's variable_get() function, but this isn't recommended if your module is storing more than one or two of these.

And again, depending on what you're doing, you may want to look into PHP's session functions which can store variables for a specific user in a method similar to cookies.

--= Jeff Robbins | www.lullabot.com =--

amino_ab’s picture

Thank you for your reply. It works fine!
However I understand that every time the user click on any link in the web site, querry will be executed and this is why I want to try a different approach : loading once the variable. Something that is very strange in drupal is that : all the modules are loaded in every navigation request which will cause a high server trafic. May be I have not yet understood how drupal runs, but I ask to understand :)
Finally, I want to understand how the declaration of $user has been done??? in which module or include file??? where is the starting point for drupal when user log-in is done? may be I add my global variables there!

jjeff’s picture

Yes, well some of this is just the way that Drupal works.. Some of this is the way that web application (unlike a desktop application) needs to work. However if you use the variable_set() and variable_get() methods, there will be some caching and all variables are loaded with a single query.

--= Jeff Robbins | www.lullabot.com =--

amino_ab’s picture

We can use hook_user with op = 'login' and then attach a new property to $user, $user->mydata = $mydata; and save it with user_save($user, 'mydata') whenever needed to be saved (update, remove of this data).


ytsurk’s picture

i had to use the $GLOBALS array

aha - interesting ..