Access a global variable in a PHP function

前端 未结 9 1984
感动是毒
感动是毒 2020-11-29 05:33

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn\'t this code work?



        
相关标签:
9条回答
  • 2020-11-29 06:16

    If you want, you can use the "define" function, but this function creates a constant which can't be changed once defined.

    <?php
        define("GREETING", "Welcome to W3Schools.com!");
    
        function myTest() {
            echo GREETING;
        }
    
        myTest();
    ?>
    

    PHP Constants

    0 讨论(0)
  • 2020-11-29 06:22

    It's a matter of scope. In short, global variables should be avoided so:

    You either need to pass it as a parameter:

    $data = 'My data';
    
    function menugen($data)
    {
        echo $data;
    }
    

    Or have it in a class and access it

    class MyClass
    {
        private $data = "";
    
        function menugen()
        {
            echo this->data;
        }
    
    }
    

    See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.

    0 讨论(0)
  • 2020-11-29 06:27

    For many years I have always used this format:

    <?php
        $data = "Hello";
    
        function sayHello(){
            echo $GLOBALS["data"];
        }
    
        sayHello();
    ?>
    

    I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

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