global variables in php not working as expected

后端 未结 7 1799
被撕碎了的回忆
被撕碎了的回忆 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:39

    It is useless till it is in the function or a class. Global means that you can use a variable in any part of program. So if the global is not contained in the function or a class there is no use of using Global

    0 讨论(0)
  • 2020-12-05 07:40

    You need to put "global $screen" in every function that references it, not just at the top of each file.

    0 讨论(0)
  • 2020-12-05 07:43

    You must declare a variable as global before define values for it.

    0 讨论(0)
  • 2020-12-05 07:47

    If you have a lot of variables you want to access during a task which uses many functions, consider making a 'context' object to hold the stuff:

    //We're doing "foo", and we need importantString and relevantObject to do it
    $fooContext = new StdClass(); //StdClass is an empty class
    $fooContext->importantString = "a very important string";
    $fooContext->relevantObject = new RelevantObject();
    
    doFoo($fooContext);
    

    Now just pass this object as a parameter to all the functions. You won't need global variables, and your function signatures stay clean. It's also easy to later replace the empty StdClass with a class that actually has relevant methods in it.

    0 讨论(0)
  • 2020-12-05 07:48

    global $foo doesn't mean "make this variable global, so that everyone can use it". global $foo means "within the scope of this function, use the global variable $foo".

    I am assuming from your example that each time, you are referring to $screen from within a function. If so you will need to use global $screen in each function.

    0 讨论(0)
  • 2020-12-05 07:50

    The global scope spans included and required files, you don't need to use the global keyword unless using the variable from within a function. You could try using the $GLOBALS array instead.

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