Making global var from inside a function in PHP

后端 未结 3 1504
栀梦
栀梦 2021-01-23 08:16

I am trying to define dynamically variables. I am using a function for this, but I don\'t know how to define the new var as global (because it never created before the function)

3条回答
  •  天涯浪人
    2021-01-23 08:41

    You can do it in two ways:

    Make the variable global using the global keyword:

    function fun1() {
            global $foo;
            $foo = 1;
    }
    

    Alternatively you can also create an new element in the $GLOBALS array:

    function fun2() {
    
            $GLOBALS['bar'] = 1;
    }
    

    Working code

    Remember that these are considered bad practice, a function should have local variables invisible outside and should get inputs through the arguments passed. You should avoid getting arguments though global variables and must completely avoid crating global variables.

提交回复
热议问题