PHP $GLOBALS: Access Global Variables with Examples

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.  

Similar Reads

PHP mb_substr Function: How it Works with Examples

You may need to get part of a text when you work with text in PHP. The mb_substr gives you…

PHP Prepared Statements in MySQL: Preventing SQL Injection

MySQL Prepared Statements in PHP are an important tool for ensuring security and optimization. They safeguard against SQL injection attacks,…

PHP array_find: How to Locate Array Values with Examples

PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match. Understand…

PHP Static Property: How It Works & Examples

PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…

PHP array_diff_key Function: How it Works with Examples

PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

PHP Loop: How Loops Work with Examples

A loop in PHP helps you run tasks without repeating the same lines. In this article, you will learn how…

PHP array_count_values: How it Works with Examples

Developers use the array_count_values function in PHP to find how many times each value appears in an array. What is…

History of PHP: From PHP/FI to Modern Web Development

You use PHP every day if you build websites, but most people do not know where it came from or…

File Handling in PHP

File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…

PHP array_intersect_uassoc: How it Works with Examples

PHP array_intersect_uassoc checks two or more arrays and returns matches. It compares both the values and the keys with a…

Previous Article

PHP array_chunk(): Split Arrays into Manageable Parts

Next Article

PHP $_SERVER: Basics and Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.