Page 1 of 1

Disappearing $GLOBALS scope

Posted: Sun Aug 08, 2004 10:01 pm
by LonelyProgrammer
Global variables just refuse to work. This is the first time I am coming across this...

a.php

Code: Select all

class a
{
  // imagine some code her
}

$g_a = new a();
b.php

Code: Select all

print_r($GLOBALS) // -- їb]BOOKMARK 1ї/b]
class b
{
 function printA()
 {
   global $g_a;
   print_r($GLOBALS); // --їb] BOOKMARK 2ї/b]
   a::someMethodFromA();
}
c.php

Code: Select all

include_once "a.php";
include_once "b.php";
b::printA(0;
Gist of the code is this - I create a global instance of class a. In b.php, I attempt to access the global 'a' instance. It works - or it used to work, and is still working, but just not for the particular code I am writing?

I decide to check for $g_a scope. Suprisingly, in b.php, print_r($GLOBALS) (Bookmark 1) dump all the global variables along with the instance of $g_a. However, once entering the function scope (Bookmark 2), print_r($GLOBALS) yields nothing!

I have to declare the variables as below to get it working

In a.php

Code: Select all

global $g_a;
$g_a = new a();
Is it worth mentioning that a.php and b.php are in seperate folders above c?

That is...

c is in c:\code
a and b are in c:\code\library

Many thanks in advance!

Posted: Sun Aug 08, 2004 11:55 pm
by feyd
to access a global inside a function, you must use the "global" keyword, or access it through the $GLOBALS superglobal. This is how php works right now.