Search code examples
phpglobal-variables

PHP - Global variables being cleared


I have a PHP file imported by a require_once() call in another PHP file that is autoloaded. In this file there are a small number of string global variables defined:

$foobar = "foo";
$bazqux = "baz";

class FooClass {
    private $foo;

    public function __construct() {
        global $foobar;
        $this->foo = $foobar; // $foobar is <null> here
    }
}

However, when I run this code the global variable $foobar is "" according to XDebug under Apache2 (I'm using VS.php as my IDE). I get the same problem when I run the script under normal PHP FastCGI under IIS .

I've gone through all my code and the symbol "$foobar" only appears in this source file so it isn't being overwritten elsewhere.

I since changed it from a global variable to a define() constant and it works fine.

Any ideas?


Solution

  • Use the superglobal - $GLOBALS.

    $this->foo = $GLOBALS["foobar"];
    

    EDIT:

    <?php
    $foobar = "foo";
    $bazqux = "baz";
    
    class FooClass {
        private $foo;
    
        public function __construct() {
            global $foobar;
            $this->foo = $foobar;  
        }
        function display() {
          print $this->foo;
        }
    }
    
    $a=new FooClass;
    print $a->display();
    ?>