tags:

views:

52

answers:

2

I have php file with a class in it that needs to read a variable from my config file. The config file is getting included in both the page thats including the class and the class itself (both with require_once). However, the variable i need to read ($cfg) is apparently undefined in the class file, according to the errors i'm getting:

Notice: Undefined variable: cfg in /opt/lampp/htdocs/screia/obj/MemberProfile.class.php on line 45

I tried making it global in the config file by adding:

global $cfg;

but it still wont find it. I had a suggestion from a friend that maybe with the new namespacing in 5.3.0 they changed the semantics of including. is this true?

A: 

In the class file on the line that is throwing the notice try prefixing $cfg with global e.g. global $cfg before reading the variable.

Also, check the contents of $GLOBALS in the class file, such as isset($GLOBALS['cfg'])

pygorex1
+2  A: 

You're misunderstading how global works. You must put it in the body of the function using that variable. Such as:

class Something {
    function foo() {
        global $cfg;
        // Code using $cfg here
    }
}

That should work for you. It is, however, a bad practice to use global, you should consider passing the needed configuration to the class when you instance it, or through a method.

Juan
You can also consistently access it using $GLOBALS['cfg'];
preinheimer