Understanding the PHP $GLOBALS variable
Asked Answered
O

4

8

I am learning PHP from w3schools' PHP Tutorial.

While learning PHP I came across the concept of predefined global variables i.e. Superglobals.

In a curiosity to understand "Superglobals" more deeply I wrote the following code and executed it in a browser on my local machine(i.e.localhost) :

<!DOCTYPE html>
<html>
  <body>

  <?php
    echo "<pre>";
    print_r($GLOBALS);
    echo "</pre>";
  ?>

  </body>
</html>

I got following output in a browser :

Array
(
    [_GET] => Array
        (
        )

    [_POST] => Array
        (
        )

    [_COOKIE] => Array
        (
            [toWorkNormally] => 1
        )

    [_FILES] => Array
        (
        )

    [GLOBALS] => Array
 *RECURSION*
)

The above output has created many doubts in my mind as follows :

  1. As per my knowledge in PHP there are nine types of superglobals (predefined PHP global variables) viz. $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE and $_SESSION then my doubt is what does the array elements from the predefined global array $GLOBALS viz. [_GET], [_POST], [_COOKIE], [_FILES] mean as they have their own independent existence as superglobals?
  2. What is meant by [toWorkNormally] => 1 from above array output?
  3. What does mean by RECURSION in element [GLOBALS] and how to print those elements?
  4. As the purpose of $GLOBALS array is to store variables declared by user globally then how this array has been pre-populated with some other values as I haven't declared any global variable in my code?

Note : I'm using "Microsoft Windows 10 Home Single Language" operating system on my machine. It's a 64-bit Operating System. I'm using latest edition of XAMPP with PHP 7.0.13 and HTTP Apache web server v.2.4.23 for running the program locally. Also, please note that I have not defined any other variable as global or local in my code.

Outrigger answered 7/1, 2017 at 18:0 Comment(5)
execute from terminal.Coherence
@Coherence : I'm using a machine running on Windows10 Home Single Language operating system and using XAMPP server setup program then how could I run from terminal I don't know.Outrigger
just type php file.phpCoherence
@Coherence : in the address bar of a browser like we type in the URL?Outrigger
access this link link editrocket.com/articles/php_windows.htmlCoherence
P
3

From my knowledge of PHP and doing some research as well as testing this on multiple OS' with various version of PHP I found the following.

Question 1 & 3:

Yes you are correct with regards to the 9 superglobals, but a very important thing to keep in mind is that $GLOBALS -- References all variables available in global scope.

An interesting sidenote, notice that $GLOBALS is the only superglobal that doesn't start with an underscore.

Because of the fact that $GLOBALS contains references to all the other superglobals including itself, when we print_r($GLOBALS) it will also include the other superglobals in the output. Because $GLOBALS references itself as well we get the RECURSION you asked about in your 3rd point. You can think of it as a infinite dimensional array containing $GLOBALS. Almost the same idea as an infinte loop.

[GLOBALS] => Array
    (
        [GLOBALS] => Array
            (
                [GLOBALS] => Array
                    (
                        ...
                    )
            )
    )

Instead the script sees this and stop executing and just prints RECURSION. Now I have tested it on 3 different environments and each time the order in which the superglobals are printed changed, but as soon as it hits $GLOBALS it stops and prints RECURSION.

Question 2:

I could not find any info on $_COOKIE[toWorkNormally] => 1. I am assuming this is set somewhere else. I didn't see it in any of my tests.

Question 4:

This is neither correct nor incorrect. The purpose of $GLOBALS is not to store all variables created by the user globally. It merely references all variables available in global scope including, the superglobals. That is why you are seeing all the other superglobals in the output. But a lot of developers assume that the user defined global variables are stored in $GLOBALS.

Description in the PHP.net manual

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

To view all the superglobals you will have to print_r() each one of them individually.

To check all user defined global variables you can use array_keys($GLOBALS) all the items which are not superglobals will most probably be user defined global variables.

EDIT in response to users comments

In response to your 1st comment, No they are not different. The superglobals not printed are still part of the array but execution/output stops because it hits the RECURSION when it gets to $GLOBALS. The superglobals are printed in a random order and which ever comes after the $GLOBALS will not be seen as it detects a RECURSION at $GLOBALS and stops the output.

You can check all the superglobals/global variables by using print_r(array_keys($GLOBALS)); With an exception of $_SESSION because a session has not been started yet. print_r($_SESSION) will give you an undefined variable $_SESSION Notice. You will be able to see $_SESSION when you put session_start(); just before you print it.

Link to What References Are in PHP

References in PHP are a means to access the same variable content by different names.

Note that in PHP, variable name and variable content are different, so the same content can have different names

Polash answered 10/1, 2017 at 10:27 Comment(6)
As you are saying the "$GLOBALS -- References all variables available in global scope" then where are the references to other global variables viz. $_SERVER, $_REQUEST, $_ENV and $_SESSION in $GLOBALS array? Are the superglobals $_SERVER, $_REQUEST, $_ENV and $_SESSION are different in any sense from the superglobals $_GET, $_POST, $_COOKIE and $_FILES?Outrigger
This comment is regarding your answer for Question no.4. I created a global variable as $a = "Mango"; Then again I executed the code print_r($GLOBALS); This time in output it contained [a] => Mango. This means [a] => Mango(a key-value pair) has become part of the global array $GLOBALS. Then tell me referencing to the user defined global variable, containing the user defined global variable, storing the user defined global variable are the different things with different meaning?(contd. in next comment)Outrigger
(in conj. with above comment) As it's displaying the user defined global variable as part of array $GLOBALS then how could you say that it only references global variables and not contains them?Outrigger
@user2839497 I made an EDIT to the answer in response to your comments.Polash
I tried executing this code <?php $jumbo = "Mango"; print_r($GLOBALS); ?> and got the output as Array ( [_GET] => Array ( ) [_POST] => Array ( ) [_COOKIE] => Array ( ) [_FILES] => Array ( ) [GLOBALS] => Array RECURSION [jumbo] => Mango ) From the output you can see that even after RECURSION the user defined global variables are getting printed. Then how can you claim that "execution/output stops because it hits the RECURSION when it gets to $GLOBALS" and "which ever comes after the $GLOBALS will not be seen as it detects a RECURSION at $GLOBALS and stops the output"?Outrigger
I also tried the code <?php print_r(array_keys($GLOBALS)); ?> and got the output Array ( [0] => _GET [1] => _POST [2] => _COOKIE [3] => _FILES [4] => GLOBALS ). Still missing other superglobals. Why?Outrigger
N
0

$GLOBALS is the global of all super global and user defined variables. So for example if you have declared variable $a = 10; in your $GLOBALS array you have key=>value pair where key is a and value is 10.If you want to get something from $GLOBALS you just need to write it as array key.

example

$a = 25;
echo $GLOBALS['a'];

In the example above output will be the value of $a so 25;

In your example toWorkNormally=>1 it`s mean that you have set cookie with name toWorkNormally and with value 1 or true

Also when you submit form with get or post method in the $GLOBALS['_GET'] or $GLOBALS['_POST'] there you can find your form data as you can get them from super global $_GET or $_POST

Nonfiction answered 7/1, 2017 at 18:16 Comment(0)
I
0

The PHP manual says the following about the $GLOBALS variable:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

This describes exactly what the variable does. It is simply a reference to existing variables.

The RECURSION you are talking about is the $GLOBALS variable referring to itself. Since we don't want PHP to endlessly output the same output and crashing your server in the process, there is a built-in failsafe that shows you the RECURSION alert if this is the case.

I would like to add that $GLOBALS is a superglobal, or preset global, variable. This means that it is available in all scopes throughout your script.

Resources

Intervene answered 10/1, 2017 at 11:22 Comment(0)
H
0

1. As per my knowledge in PHP there are nine types of superglobals (predefined PHP global variables) viz. $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE and $_SESSION then my doubt is what does the array elements from the predefined global array $GLOBALS viz. [_GET], [_POST], [_COOKIE], [_FILES] mean as they have their own independent existence as superglobals?

From PHP's doc:

References all variables available in global scope

This means you can access a superglobal directly or from $GLOBALS, yes, you have two ways of accessing them.


2. What is meant by [toWorkNormally] => 1 from above array output?
It's inside $_COOKIE so there's a cookie named toWorkNormally with the value of 1. More info on cookies


3. What does mean by RECURSION in element [GLOBALS] and how to print those elements? Recursion means it refereces itself, if it was printed then it would show the contents of $GLOBALS again nested inside GLOBALS, that would cause infinite loop. To avoid that PHP just printed *RECURSION* instead.


4. As the purpose of $GLOBALS array is to store variables declared by user globally then how this array has been pre-populated with some other values as I haven't declared any global variable in my code?

From PHP's doc:

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

So in other words, $GLOBALS will show you those predefined variables from PHP and also the values you set manually.

Hartman answered 16/1, 2017 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.