Home > Linux > Server Mania’s Complete Guide To Global Variables In PHP

Server Mania’s Complete Guide To Global Variables In PHP

Hey there, folks! Today, we’re going to talk about the rather contentious subject of global variables in PHP. If you’re working with PHP, you’re probably going to run into them at one point or another – better you understand them right out the door, rather than having to learn them on the fly, right?

Shall we begin?

A Word Of Warning

Before we get started, it’s worth mentioning that global variables are something that should be used very sparingly. Not only can they be defined anywhere in the code – meaning there’s no one place to look to see what a variable’s used for – they also introduce additional parameters to your code, some of which may be impossible to document. On top of that, because of the way variables are created in PHP, there’s no way to be certain whether or not a particular variable has been created – and hence whether or not it is accessible.

Last, but certainly not least, other developers may use variables with names identical to yours – meaning that combining your code with other plugins or applications could break something fundamental.

So, I repeat, use global variables sparingly. It is also a good idea to name your variables with a prefix such as “$g_” so that you can immediately recognize them as globals when you refer to them. It’s also wise to include plenty of comments in your code regarding how the global should be used and where it is defined and modified.

However, it’s worth noting that globals in PHP are a bit different from globals in other languages, the scope being limited to a single HTTP request (which is actually smaller than session variables). Globals work a bit different in PHP and aren’t considered quite the mortal sin they would be considered in, say, C++. Globals in PHP are more like ThreadLocals in Java than true globals.

The most important thing to keep in mind is that you want dependencies to be plainly apparent and clearly spelled out (ideally in a central Registry). You should never use globals to magically teleport information.

PHP Variables: A Primer

Let’s start with the absolute basics. What is a variable? More importantly, what does a variable look like within the context of PHP?

As most of you likely know already, variables are containers that are used to store digital information. They’re used for a wide array of different functions, but they’re most often utilized in calculations, either to manipulate data or store results.

An overly simplified explanation, sure, but it’s one we can work with.

Now, in the context of PHP – as with any other language – there are a few unique rules that apply to variables:

  • A PHP variable must begin with a $, followed by its name
  • A PHP variable’s name needs to start with either a letter or an underscore; it cannot start with a number.
  • PHP variable names cannot contain symbols – only alphanumeric characters and underscores.
  • PHP variables are case-sensitive.
  • A PHP variable that contains a text string must have quotations around the string.
  • There is no command for the creation of a variable in PHP. It exists the moment it is defined; in most cases, variables are deleted once a function is finished using them.

Get all that? Good. Now that you’ve a basic understanding how how variables are defined in PHP, it’s time to move on to an explanation of scope – including, of course, how you can define a global variable.

How Variable Scope Works In PHP

Scripts in this section are courtesy of PHP.Net

A variable’s ‘scope’ refers to the context within which it is available – based, of course, on how it was defined. The vast majority of PHP variables possess only a single scope, which spans both included and required files. In broad terms, there are four different ‘scope’ types:

  • Local variables
  • Function parameters
  • Global variables
  • Static variables.

We’re going to touch on all four in this piece, but only inasmuch as they help us explain global variables – that is, after all, our focus here. At any rate, rather than spend several pages trying to explain all of this, it may simply be easier to show you:

 

<?php

$a = 1;

include ‘b.inc’;

?>

 

Here, we’ve created a variable $a, which will be available within the b.inc script. However, consider what happens when a user-defined function attempts to call upon $a, as with the following script:

 

<?php

$a = 1; /* global scope */

function test()

{

   echo $a; /* reference to local scope variable */

}

test();

?>

 

In the above example, the echo statement within the function test( ) will fail to return any data, even though $a has been defined as a global variable. This is because $a still exists as a local variable here – the global version of $a has not yet been assigned a value within the context of test( ). This is one area of PHP that tends to trip up newcomers – in order to use a global variable in a function, it must be declared as global within that function.

Alright, but…how exactly does one do that?

How To Declare A Variable As Global (and As Everything Else, Too)

If you want to set up a global variable, there are actually a few ways you can go about it. The first is to simply make use of the global keyword. This will allow you to create and define any number of standard global variables, as seen in the following example (again, credit goes to PHP.net):

 

<?php

$a = 1;

$b = 2;

 

function Sum()

{

   global $a, $b;

   $b = $a + $b;

}

 

Sum();

echo $b;

?>

This script will output the value of 3. Because both $a and $b have been declared as global within the function, all changes and references made to either will be applied to their global version – not the local version. The keyword takes already-defined global variables, and defines them again within the parameters of the function.

Now that we’ve got that out of the way, there’s actually another method for accessing and manipulating global variables – Superglobals.

Everything You Need To Know About Superglobals

A Superglobal is one of several predefined variables in PHP that is accessible within any scope. For posterity’s sake, we’ve included below a list of all the different Superglobals you can use (source). Our focus, however, will primarily be on the first item – $GLOBALS.

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

 

Consider the following script:

 

<?php

$a = 1;

$b = 2;

 

function Sum()

{

   $GLOBALS[‘b’] = $GLOBALS[‘a’] + $GLOBALS[‘b’];

}

 

Sum();

echo $b;

?>

In this example, the $GLOBALS array is used in lieu of the global keyword, returning the same value as our previous calculation – 3.  It can be used to call, access, and store any variable that has been globally defined – regardless of the scope in which it is used.

How Do Static Variables Fit In?

Before we wrap things up, it seems prudent to offer a brief explanation of static variables, and their place within the context of PHP. A static variable exists exclusively within a local scope, but retains its value when the program leaves its scope. This makes static variables valuable for storing incremental data or coding recursive functions.

It’s important to note that static variables cannot be expressions – they need to be assigned concrete values.

In Closing

At any rate, that more or less wraps up our piece on Global Variables. Hopefully you’ve a slightly deeper understanding how PHP works now – and hopefully, that helps you in your future development endeavors. See you next week!

Complete Digital Server Solutions For All

Bare Metal

Dedicated Servers

A single tenant, physical server allowing you full access to its resources.

Professional-grade

Hybrid Servers

Virtualized server platform hosted on enterprise-grade physical servers.

Managed

Colocation

Your privately owned servers and equipment secured in a top-tier data center.

Jay Caissie

Jay Caissie

Jay Caissie is the Director of IT at ServerMania.