What is the difference between global and superglobal variables?

Asked

Viewed 2,933 times

7

I read some time ago that PHP has the vast majority of its variables declared with local scope.

But I found two others concepts variables global and super-global and I didn’t quite understand the difference between the two.

  • What is the difference between global and super global variables?
  • When to (laugh) use each specific type?
  • If you can comment because the question is bad and how I can improve it would be interesting too.

2 answers

14


Super Global Variables

Super global variables are native variables of PHP and are named because they will be present in any scope of the program. They were introduced in PHP 4.1.0 and are:

  • $GLOBALS: Reference all variables available in the global scope;
  • $_SERVER: Server information and execution environment;
  • $_GET: HTTP GET request variables;
  • $_POST: HTTP POST request variables;
  • $_FILES: Files sent via HTTP POST;
  • $_COOKIE: Cookies set in HTTP request;
  • $_SESSION: Session variables;
  • $_REQUEST: HTTP request variables;
  • $_ENV: Environment variables;

The behavior of super global variables can be affected with settings such as variables_order and register_globals. Since the global variables are native, the developer is not allowed to define them. That is, there will be no other super global than the aforementioned, unless in future versions of PHP another is defined.

Variable variables

A behavior of super-global variables that differs from other variables is that they do not suffer from the behavior of variable variables in local scopes, either within functions or methods. That is, considering the code below:

function get_id() {

    $var = "_GET";

    return ${$var}["id"];
}

See working on Ideone.

Error will be cast:

Undefined variable: _GET

Even if you happen to want to include the variable in the scope (which makes no sense):

function get_id() {

    global $_GET;

    $var = "_GET";

    return ${$var}["id"];
}

See working on Ideone.

Global Variables

In turn, global variables are common variables defined in the overall scope of the application, but unlike some other programming languages, global variables are not defined in all scopes by default, it is necessary to inform when a variable is external to the local scope. This can be done using global. For example, consider the code below:

$x = 1;

echo $x, PHP_EOL;

function foo() {
    $x = 2;

    echo $x, PHP_EOL;
}

foo();

echo $x, PHP_EOL;

See working on Ideone.

Considering the natural behavior of global variables, the expected output would be 1, 2, 2, for the value of $x would be modified within the function, but in PHP the output is 1, 2, 1, because what happens is that the variable $x is local and does not affect the value of the global variable. However, indicate $x as global:

$x = 1;

echo $x, PHP_EOL;

function foo() {
    global $x;

    $x = 2;

    echo $x, PHP_EOL;
}

foo();

echo $x, PHP_EOL;

See working on Ideone

The way out will be 1, 2, 2, because now the global variable has been affected by the function.

Anonymous functions

The same happens with anonymous functions, when necessary to use external variables. For example, to multiply a list of values by a factor:

$array = [1, 2, 3, 4, 5];
$factor = 2;

function multiplica($array) {

    $factor = 5;

    $array = array_map(function ($value) {
        global $factor;
        return $value * $factor;
    }, $array);

    return $array;

}

print_r(multiplica($array));

See working on Ideone.

The result will be the multiplication of the list by factor 2, because when using global $factor the variable $factor is imported from the global scope, not from the higher scope than the current one. If there is no global variable, an unexpected result or error will be produced.

Variable variables

And contrary to the behavior of super-globals, global variables work with variables.

$foo = "SOpt";

function foo () {

    global $foo;

    $var = "foo";

    echo $$var, PHP_EOL;
}

foo();

See working on Ideone.

Provided, of course, the global variable is included in the scope of the function using the global. Otherwise, the variable will not be defined, generating the error:

$foo = "SOpt";

function foo () {
    $var = "foo";

    echo $$var, PHP_EOL;
}

foo();

See working on Ideone.

All global and super global variables will meet on array associative defined in $GLOBALS. Being this a super global variable, it can be used in any scope, but it is worth remembering that local variables to this scope will not be included in array, only the global.

When to (laugh) use each specific type?

The super global variables you use when you need some value defined by PHP in the variables mentioned at the beginning of the answer. That is, if you need to access the value of a session, $_SESSION, or retrieve information from the web server, $_SERVER. As stated earlier, there is no way the developer can define a new super global variable, only use them when necessary. In turn, global variables should be used when this makes sense for their application. That is, when a function makes use of some external value and that is not semantic pass it by parameter. A practical example could be an application log file; assuming the function exists add, adding two values and managing their log:

function add($x, $y, $handle_log) {
    $result = $x + $y;

    fwrite($handle_log, "O resultado da soma {$x}+{$y} foi {$result}");

    return $result;
}

The use of function would be something like this:

$handle_log = fopen("log.txt", "w");

$result = add(1, 2, $handle_log);

echo $result;

Realize that it doesn’t make much sense for you to have to pass $handle_log as a function parameter where its goal is just to add two values. An alternative would be:

$handle_log = fopen("log.txt", "w");

function add($x, $y, ) {
    global $handle_log;

    $result = $x + $y;

    fwrite($handle_log, "O resultado da soma {$x}+{$y} foi {$result}");

    return $result;
}

$result = add(1, 2);

echo $result;

Making the function call make sense according to the purpose of the function. There are many other alternatives besides this, possibly much more elegant, but it is an example. In short, you can/should use a global variable when it makes sense for your solution.


Interesting readings:

Why using global variables is not a good practice?

  • 1

    Nice explanation +1

10

The difference is that the super global there is no need to inform global $variavel, you simply access. They are available in all scopes, they are:

  1. $GLOBALS
  2. $_SERVER
  3. $_GET
  4. $_POST
  5. $_FILES
  6. $_COOKIE
  7. $_SESSION
  8. $_REQUEST
  9. $_ENV

Already the global variables (not super ones), to have access to it in different scopes, you need to inform global $variavel before using it (in each scope). Only after this command will it be available to you in the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.