global variables in php not working as expected

后端 未结 7 1800
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 07:33

I\'m having trouble with global variables in php. I have a $screen var set in one file, which requires another file that calls an initSession() def

相关标签:
7条回答
  • 2020-12-05 07:51

    Global DOES NOT make the variable global. I know it's tricky :-)

    Global says that a local variable will be used as if it was a variable with a higher scope.

    E.G :

    <?php
    
    $var = "test"; // this is accessible in all the rest of the code, even an included one
    
    function foo2()
    {
        global $var;
        echo $var; // this print "test"
        $var = 'test2';
    }
    
    global $var; // this is totally useless, unless this file is included inside a class or function
    
    function foo()
    {
        echo $var; // this print nothing, you are using a local var
        $var = 'test3';
    }
    
    foo();
    foo2();
    echo $var;  // this will print 'test2'
    ?>
    

    Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid global if you can.

    0 讨论(0)
提交回复
热议问题