开发者

PHP 5.3.0 funky problem with including

开发者 https://www.devze.com 2022-12-14 19:45 出处:网络
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 req

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 requ开发者_开发技巧ire_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?


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.


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'])

0

精彩评论

暂无评论...
验证码 换一张
取 消