6
<?php

$foo = 1;

function meh(){
  // <-- $foo can't be accessed
}

It doesn't look like a global variable. However, does it have disadvantages like global stuff if it's outside the function?

TheSoldier
  • 474
  • 1
  • 5
  • 17
Alex
  • 60,472
  • 154
  • 401
  • 592

6 Answers6

9

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

siddhant3s
  • 370
  • 2
  • 9
7

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

Community
  • 1
  • 1
Gordon Gustafson
  • 36,457
  • 23
  • 109
  • 151
5
<?php

$foo = 1;

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

?>
Alex Rodrigues
  • 1,887
  • 11
  • 9
2

Outside of the function is sorta like global scope (when compared to C-like languages), but you have to do one thing to allow access to the var within a function:

function meh(){
  global $foo;
  // $foo now exists in this scope
}
SamT
  • 9,464
  • 2
  • 29
  • 37
2

In your example $foo gets created as variable in the global scope. (Unless your shown script was included() from within another functions/methods scope.)

PHP doesn't have real global variables. You have to manually alias it using the global $foo; statement to access them. (Also the "anything global is bad" advise is just that, bad advise.)

mario
  • 138,064
  • 18
  • 223
  • 277
2

If I understand your question correctly, there really shouldn't be a problem. Unless you declare a variable as a global, it will been limited to the scope in which it is declared, in this case whatever php file the above code is defined in. You could declare another variable $foo in meh() and it would be independent of the $foo defined outside.

duanemat
  • 217
  • 1
  • 6
  • 12