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.
Table of Content
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.
Similar Reads
The PHP array_find_key function finds a key in an array by a condition. It checks each element and returns the…
The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…
In PHP, if you're working with XML files, you’ll probably work with DOMDocument. It is a powerful class, enabling you…
The array_rand() is a helper function in PHP that makes it easier when dealing with arrays; you can just pull…
Understanding PHP syntax is like the basics of any language—PHP syntax defines the rules for writing code that a server…
Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…
Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…
The substr() function in PHP returns part of a string. You give it a string, a starting point, and optionally…
Connecting PHP to MySQL is not just a technical step—it is the basic part of how data-driven websites work. From…
The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…