On 11 Mar 2012, at 01:43, Tedd Sperling wrote:

> On Mar 10, 2012, at 3:53 PM, tamouse mailing lists wrote:
>> On Sat, Mar 10, 2012 at 9:37 AM, Tedd Sperling <tedd.sperl...@gmail.com> 
>> wrote:
>>> That's correct, but to access those variables outside of their scope (such 
>>> as a function) you do via a SuperGlobal, namely $GLOBAL['whatever'].
>>> As such, there are no "globals" in PHP other than SuperGlobals. As I said, 
>>> if I'm wrong, please show me otherwise.
>> I guess I don't know what you mean by "globals". I know what globals
>> are, but not "globals".
> I don't understand your question. I know what questions are, but not your 
> question. :-)

I think the confusion is arising because the word superglobal is used in PHP 
when referring to globals, because the word global has been incorrectly applied 
for quite some time.

A global variable is a variable that is accessible in every scope, so Tedd is 
right… the only true globals in PHP are the superglobals. Here's an overview of 
the various scopes in PHP (I've probably missed some, but it's enough to make 
the point)…

  // Only visible when not in a function or class. The PHP manual calls
  // this the "global" scope: http://php.net/variables.scope
  $var1 = 'a';

  function funcB()
    // Only visible inside this function.
    $var2 = 'b';

  function funcB()
    // This statement makes the variable from the top-level scope visible
    // within this function. Essentially this is the same as passing the
    // variable in to the function by reference.
    global $var1;

  class classC
    // Visible to methods in this class only.
    private $var3 = 'c';

    // Visible to methods in this class and methods in derived classes.
    protected $var4 = 'd';

    // Method visible in this class only.
    private methodA()
      // Visible only inside this method.
      $var5 = 'e';

    // Method visible in this class and methods in derived classes.
    protected methodB()
      // See funcB()
      global $var1;

    // Method visible on any instance of this class.
    public methodC()
      // See funcB()
      global $var1;

The global keyword allows you to expose a variable that has been defined at the 
top-level scope ($var1 in the above example) in the current scope. It does NOT 
create a global variable; the keyword is not an accurate reflection of what it 

My guess is that calling the top-level scope "global" made sense when functions 
were the only other level of scope that existed. Now that we have yet more 
levels of scope it can be a bit confusing.

I hope this helps clear things up.


Stuart Dallas
3ft9 Ltd
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to