PHP: Global variable scope

前端 未结 5 540
天命终不由人
天命终不由人 2020-12-22 12:26

I have a separate file where I include variables with thier set value. How can I make these variables global?

Ex. I have the value $myval in the v

5条回答
  •  清酒与你
    2020-12-22 13:07

    Inside the function, use the global keyword or access the variable from the $GLOBALS[] array:

    function myfunc() {
      global $myvar;
    }
    

    Or, for better readability: use $GLOBALS[]. This makes it clear that you are accessing something at the global scope.

    function myfunc() {
      echo $GLOBALS['myvar'];
    }
    

    Finally though,

    Whenever possible, avoid using the global variable to begin with and pass it instead as a parameter to the function:

    function myfunc($myvar) {
      echo $myvar . " (in a function)";
    }
    
    $myvar = "I'm global!";
    myfunc($myvar);
    // I'm global! (in a function)
    

提交回复
热议问题