Global variable, visible only inside the module I have several modules, that implement very close functionality. And the SQL requests are almost the same, except for the table name. So I wanted to create a global variable, inside each module:

$GLOBALS['module_name'] = __FILE__;
$regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
$GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);


$GLOBALS['module_name'] will contain the current file name, which is the same as name of the table.

And then use it in the requests:

$query = db_select($GLOBALS['module_name']);


But global variables are shared among the modules, and the definition from a different module rewrites the correct value.

I tried to use hook_init

function my_module_init()
{
   $GLOBALS['module_name'] = __FILE__;
   $regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
   $GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);
}


But without success.

Is it possible to have global variables with the same name in many modules, but each will be visible only inside the appropriate module?
If you use the same global variable, its value is shared between all the enabled modules because global variables are globals by definition. Every PHP file that is loaded will see the same global variables, such as the global $user that is used from Drupal for the account of the currently logged-in user.

The same is true if you use constants defined with define(); they are global, and two modules cannot define the same constants. Try defining the REQUEST_TIME in Drupal 7, with define('REQUEST_TIME, 'test'): You will get an error, as the same constant is already defined from Drupal (see REQUEST_TIME).

The same is true for Drupal variables defined with variable_set(). Every module that is using variable_set($name, $value) (where $name has the same value for all the modules) is setting the same variable.

Even if you would be using &amp;drupal_static($name, $value) in different modules, the modules will be altering the same static variable.

I would rather use a constant defined with define(), but every module needs to use a different constant.
See the Drupal coding standards about naming conventions.