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

Install PHP on Operating System: Ubuntu, Windows, and macOS

In this tutorial, you will learn how to install PHP on your Operating system such as Ubuntu, Windows, or macOS.…

PHP Resource Type | How the get_resource_type() Works

In this tutorial, I will explain what does mean the PHP resource and we are going to cover all PHP…

PHP SimpleXML: Work with XML in Examples

PHP SimpleXML - invented for you to work with XML. Way leaner, quicker to get up. it's already integrated directly…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP trim(): How to remove Whitespace from String

Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

PHP array_intersect Function: How it Works with Examples

The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…

PHP array_column: How to Extract Values from Arrays

The array_column function in PHP takes values from one column in a multidimensional array. You can use it to pull…

PHP Multidimensional Arrays: Data Manipulation

In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…

Traits in PHP: What They Are & Examples

PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…

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.