PHP: Global variable scope

前端 未结 5 527
天命终不由人
天命终不由人 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:03

    Using the global keyword in the beginning of your function will bring those variables into scope. So for example

    $outside_variable = "foo";
    
    function my_function() {
       global $outside_variable;
       echo $outside_variable;
    }
    
    0 讨论(0)
  • 2020-12-22 13:04

    Is there a reason why you can't pass the variable into your function?

    myFunction($myVariable)
    {
      //DO SOMETHING
    }
    

    It's a far better idea to pass variables rather than use globals.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-22 13:07

    Same as if you declared the variable in the same file.

    function doSomething($arg1, $arg2) {
        global $var1, $var2;
        // do stuff here
    }
    
    0 讨论(0)
  • 2020-12-22 13:16

    Use inside your function :

    global $myval;
    

    PHP - Variable scope

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