PHP Quick Tip: Scoping Variables

One of the things I struggled the most with in my adventures in PHP programming was scoping variables.

Once I discovered the PHP keyword globals it all made sense.

The globals keyword can be expressed in two different ways. Both within a function or other sub-structure of the main script.

I’ll demonstrate both in the example below.


//Declaring variables
$a = "This is a global variable";
$b = "This too, is a global variable";

function globalx() {

   	global $a;     //this tells the function to use the contents of variable "a" declared in the main script 

	$b = "This isn't a global variable";   //this declares the variable "b", telling the function to ignore the value given to "b" in main script  

	return 'A is: '.$a.'  B is: '.$b.'  But this is... '.$GLOBALS["b"]; 
     /* it is important to note that the variable "b" must be in quotes without the $ when using the $GLOBALS keyword */

echo globalx();


The output of the above script looks like this:

A is: This is a global variable
B is: This isn’t a global variable
But this is… This too, is a global variable

I recently read a blog post that discouraged the use of global variables, stating that “good programmers” don’t use them because they can cause confusion when trying to keep track of which variable belongs to which scope.

My response to this is that good programmers name their variables in such a fashion as to avoid confusion.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s