global keyword outside the function in php

后端 未结 2 1771
执念已碎
执念已碎 2021-02-19 23:13

As we know, global keyword makes variable( or object, array) visible inside current function we are dealing with



        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 23:39

    From the docs:

    Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

    Essentially you could have your function guts in a different file than your function declaration. These guts would then be included into the function. This would give the impression, if you view the guts alone, of a user using global outside of a function, however the fact is that when this code is interpreted, it will be interpreted from within a function.

    $name = "Jonathan";
    
    function doSomething () {
      include( 'functionGuts.php' );
    }
    

    Where the contents of our functionGuts.php file could be:

    global $name;
    echo "Hello, " . $name;
    

    When viewed on its own, functionGuts.php will give the impression that global is being used outside of a function, when in reality it's being used like this:

    $name = "Jonathan";
    
    function doSomething () {
      global $name;
      echo "Hello, " . $name;
    }
    

提交回复
热议问题