$Globals

Last updated on

When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this, PHP has an extremely special variable: $GLOBALS. It's an extremely useful utility, especially when you're tackling complex applications or even just keeping track of data across functions and scripts without losing its scope.

Let's keep it simple. Think of $GLOBALS in PHP as the big bucket where you can toss variables you want to use anywhere in your code with no special pass required!

In this tutorial, you will know exactly how PHP $GLOBALS works and how to use it with examples. You will also know just how to control your PHP code using $GLOBALS like a professional developer.

What is $GLOBALS and Why Use It in PHP?

$GLOBALS is a superglobal array in PHP, meaning it can be accessed from any place within your script, whether you're in a function, a loop, or the main body of your script.

So, what would that be used for?

Imagine that you have set a variable in the main body of your script, but you want to access it inside a function. Normally, variables in PHP are bound by scope - that means they are only accessible to the portion of the script where they were originally declared.

This is where $GLOBALS saves the day. This helps you avoid the chore of passing variables through continuously, especially when you deal with several functions or larger scripts.

In the next section, you will learn how you could set and access variables using $GLOBALS, and see more examples.

Setting and Accessing Variables with $GLOBALS in PHP

Using $GLOBALS is as easy as assigning or accessing a value in an array. Let's say you have a variable, $message, that you want to make available globally. Here's how you'd do it:  

$message = "Hello, World!";

function printMessage() {
    echo $GLOBALS['message'];
}

printMessage(); // Outputs: Hello, World!

Now, in the next section, let's consider a few examples of how to use $GLOBALS within a larger PHP application to streamline code.

Example of PHP $GLOBALS

Let's get down to a pragmatic case: suppose you have an elementary shopping cart, and you want to store the total cost or the list of items that are bought in the $GLOBALS so that it is available through your checkout functions. Here is an example:

$cartTotal = 0;

function addItemToCart($itemPrice) {
    $GLOBALS['cartTotal'] += $itemPrice;
}

addItemToCart(20);
addItemToCart(15);
echo $GLOBALS['cartTotal']; // Outputs: 35

This allows $GLOBALS['cartTotal'] to be almost like a running total of the cart, since every time this addItemToCart(); runs, it will auto-update itself. In larger applications, this can simplify how you need to handle data that many parts of your code may need to access or modify.  

In the next section, we'll compare $GLOBALS with the global keyword - another way of accessing variables globally in PHP - and talk about when you might use one rather than the other.

PHP $GLOBALS vs. the global Keyword

PHP actually provides you with two different ways that allow you to share variables across scopes: $GLOBALS and the global keyword. While both work similarly, they function just a little bit differently.  

So, with the global keyword, you declare that the variable is global inside your function, like so:  

$message = "Hello, Universe!";

function printMessage() {
    global $message;
    echo $message;
}

printMessage(); // Outputs: Hello, Universe!

Unlike $GLOBALS, the global keyword allows for direct use of the variable name, rather than having to store it in the $GLOBALS array. However, global works only within the scope of the current file—so it can be a bit limited in comparison with $GLOBALS.

In the following section, will provide a quick summary along with a few take-home points to keep in mind as you start working with $GLOBALS in your projects.

Wrapping Up

In this article, I have explained PHP $GLOBALS in all their intricacies—from basic usage to the real-life application and best practices of this superglobal. You have seen how using $GLOBALS can ease your work by enabling access to variables from functions and scripts anywhere in your code.

If you’re just starting out, try applying $GLOBALS in a small project, such as a simple counter or shopping cart, within the framework of your coding style. Remember also to always keep an eye open to see whether global variables are necessary or if another method, like passing parameters, could work better.  

Thank you for reading. For more tutorials click here. Happy Coding!  

Frequently Asked Questions (FAQs)

  • What is PHP `$GLOBALS`?

    PHP $GLOBALS is a superglobal array that allows access to global variables from anywhere in your script. It helps you manage data across functions and scopes without needing to pass variables repeatedly.
  • When should I use PHP `$GLOBALS`?

    Use $GLOBALS when you need to access a variable globally across multiple functions or sections of your code. It’s especially helpful in larger scripts, but avoid overusing it as it can make debugging and tracking variable changes harder.
  • How do I set and access a global variable with `$GLOBALS`?

    To set a global variable, add it to $GLOBALS with a key. For example:
    $message = "Hello, World!"; 
    function printMessage() { echo $GLOBALS['message']; } 
    printMessage(); // Outputs: Hello, World!
  • What is the difference between `$GLOBALS` and the `global` keyword?

    Both $GLOBALS and global let you access variables globally, but $GLOBALS uses an array to store variables, while global allows direct use of variable names within functions.
    The global keyword only works within the current file’s scope, while $GLOBALS can be accessed anywhere.
  • Can I use `$GLOBALS` in a PHP function?

    Yes, you can access $GLOBALS within functions. It provides a way to access variables from the main script scope inside functions without passing them as parameters.
  • What are the drawbacks of using `$GLOBALS`?

    Using $GLOBALS too much can lead to "spaghetti code" where variables are scattered throughout your script, making it difficult to manage and debug. It’s best to use it sparingly and document global variables clearly.
  • Is `$GLOBALS` safe to use in professional PHP projects?

    While $GLOBALS can be useful, it’s generally avoided in professional projects due to the potential for complex debugging and unpredictable changes. For clean and maintainable code, consider alternative approaches, such as passing variables as function arguments.
  • Can I modify a variable in `$GLOBALS` within a function?

    Yes, you can modify $GLOBALS variables within a function by accessing them directly. For example:
    $count = 10; 
    function incrementCount() { $GLOBALS['count'] += 1; } 
    incrementCount(); echo $GLOBALS['count']; // Outputs: 11
  • How do I check if a variable exists in `$GLOBALS`?

    Use the isset() function to check if a variable exists in $GLOBALS. For example:
    if (isset($GLOBALS['username'])) { echo "Username is set."; } else { echo "Username is not set."; }
  • Can I store arrays or objects in `$GLOBALS`?

    Yes, you can store arrays, objects, or any data type in $GLOBALS. It acts like an associative array and can hold complex data structures.
Share on: