Global Variables are coming to town

Just the Gist

Global variables are accessible from anywhere in your code with the global keyword. Superglobals are available anywhere without ever using the global keyword. The superglobals allow us to do some fancy things around web-related things, like greeting the user by their name 😎

Around the Globe

Global variables are available anywhere in the application. Usually we access a global variable with global $serverName. When PHP provides us with global variables we call them Superglobals, and no global keyword is required. The following are the superglobals:

  • $GLOBALS - An associative array containing all global variables, even user-defined ones.
  • $_SERVER - Information provided by the server about headers, paths, and script locations.
  • $_GET - An associative array of variables passed to the current script via the HTTP GET method.
  • $_POST - An associative array of variables passed to the current script via the HTTP POST method.
  • $_FILES - Contains uploaded file information. POST method uploads
  • $_COOKIE - An associative array of variables passed to the current script via HTTP cookies.
  • $_SESSION - An associative array containing session variables available to the current script. These variables are available across multiple script calls.
  • $_REQUEST - An associative array containing both GET and POST variables.
  • $_ENV - An associative array containing all environment variables.

πŸ’‘ They are all associative arrays. In PHP that means that they are indexed by variable name. So, coming from JavaScript it has a similar structure to objects, and compared to Java they look like maps. This is how an associative array is structured:

$array = [
    'name' => 'Rasmus'
];

We can access the value of the name key by using $array['name'].

REQUEST has either GET or POST

Sometimes we want to access the data from either GET and POST. The $_REQUEST superglobal is a combination of both. So here's how it looks like when we have a page that contains both forms. A visitor may fill in their name and submit it with either method. We then see the use of sessions and how we can "persist" the name for a later visit, using the $_SESSION superglobal.

Note: We need to start a session before we can use the $_SESSION superglobal. We name it greetings just because we can πŸ˜‰

<?php 
    session_name('greetings');
    session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Let's load us some Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <title>Greetings!</title>
</head>
<body>
    <div class="col-lg-8 mx-auto p-3 py-md-5">
        <main>

            <?php 

                $name = 'Guest';
                if (key_exists('name', $_REQUEST)) {
                    $name = $_REQUEST['name'];
                    $_SESSION['name'] = $name;
                } 

                if (key_exists('name', $_SESSION)) {
                    $name = $_SESSION['name'];
                }

            ?>


            <h1>Hello, <?php echo $name; ?></h1>

            <h2 class="mt-4">GET Form</h2>
            <form class="d-flex">
                <div class="form-floating">
                    <input class="form-control" id="name-input" type="text" name="name" placeholder="Guest">
                    <label  for="name-input">Name</label>
                </div>
                <input class="btn btn-primary" type="submit" value="Update Name">
            </form>

            <h2 class="mt-4">POST Form</h2>
            <form class="d-flex" method="POST">
                <div class="form-floating">
                    <input class="form-control" id="name-input" type="text" name="name" placeholder="Guest">
                    <label  for="name-input">Name</label>
                </div>
                <input class="btn btn-primary" type="submit" value="Update Name">
            </form>

        </main>

    </div>
</body>
</html>

Here's our superglobals in action πŸ‘‡
First a POST request to update name to 'Anders', then a GET request to update the name to 'Jupiter'. This is stored in the session variable and will be available on the next visit.

What about you?

Have you used superglobals? Are they a nice feature, or do you see them as a scourge upon this language? Comment below and let us know what you think ✍

Further Reading

18