Are variables outside functions global variables?

All variables defined outside any function are declared in global scope. If you want to access a global variable you have two choices:

  1. Use the global keyword

    <?php
    $a = 1;
    $b = 2;
    
    function Sum()
    {
        global $a, $b;
    
        $b = $a + $b;
    }
    ?> 
    
  2. Or use the $GLOBALS

    <?php
    $a = 1;
    $b = 2;
    
    function Sum()
    {
        $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
    } 
    ?>
    

    Read more at http://php.net/manual/en/language.variables.scope.php


Yes. They can be accessed from any location, including other scripts. They are slightly better as you have to used the global keyword to access them from within a function, which gives more clarity as to where they are coming from and what they do.

The disadvantages of global variables apply, but this doesn't instantly make them evil as is often perceived in some OO languages. If they produce a good solution that's efficient and easily understandable, then you're fine. There are literally millions of succesful PHP projects that use global variables declared like this. The biggest mistake you can make is not using them and making your code even more complicated when it would have been perfectly fine to use them in the first place. :D


<?php

$foo = 1;

function meh(){
  global $foo;
  // <-- $foo now can be accessed
}

?>