Page 1 of 1

Global variable scope

Posted: Wed Jan 16, 2008 10:06 am
by dandan2907
Everah | Please use the bbCode [code] tag when posting code in the forums. To highlight PHP, please use [code=php].

I have a problem with the global scope.
I use a global variable named $db and then I include a DBConnector file that does all the work and initiates the variable as an object. When I print the result in the end of the DBConnector file I see that it was built properly.
But when I return to the original file the object is unset and the system doesn't recognize it!!!!!


My settings file ends with the following lines:

Code: Select all

global $db;
  include('DBConnector.php');
  echo "$db settings";
The DBConnector file consists of the following:

Code: Select all

if( defined( '_ADMIN_DBCONNECTOR_PHP' ) ) return;
    define( '_ADMIN_DBCONNECTOR_PHP', 1 );
include('dblayer.php');
global $db;
$db = new DBLayer();
$db->connect($SQL_SERVER,$SQL_USERNAME,$SQL_PASSWORD,$SQL_DBNAME);
 
function getNextAutoIncrement($tableName)
{
    global $db;
    //$sql = "SHOW TABLE STATUS WHERE Name='".$tableName."'";
    $sql = "SHOW TABLE STATUS WHERE Name='".$tableName."'";
    $tableStatus = array();
    $db->Query($tableStatus,$sql);
    return $tableStatus[0]['Auto_increment'];
}
 
echo "$db connector";
 
printing the $db variables I get the following line:

"Object connectror settings"
means that the first time I print $db the system recognizes an Object but the second time (in the settings file) it doesn't!!!!
Does anyone know Why?
Thanks
Danny

Everah | Please use the bbCode [code] tag when posting code in the forums. To highlight PHP, please use [code=php].

Re: Global variable scope

Posted: Wed Jan 16, 2008 11:17 am
by jimthunderbird
Strange...

Maybe you defined '_ADMIN_DBCONNECTOR_PHP' somewhere in your setting file..., so when you include your DBConnector file, it just return, thus not initiating the db object. :?

Re: Global variable scope

Posted: Wed Jan 16, 2008 3:19 pm
by dandan2907
Could be nice if life were so simple..
The thing is that after the db variable is instantiated in DBConnector.php it ceases to exist in settings.php
How come?
Does anyone knows about forums where I can post PHP questions?
Danny

Re: Global variable scope

Posted: Wed Jan 16, 2008 7:04 pm
by RobertGonzalez
Try this, without using any of your current code.

Code: Select all

<?php
$db = 'This should be my link identifier';
 
function blahblah() {
  global $db;
 
  echo $db;
}
 
function noglobal() {
  // This should throw an warning about an undefined variable
  echo $db;
}
 
blahblah(); // Echos out the $db var
noglobal(); // issues a warning
?>
What does this code do for you on your system?