17 WEBSHOP [web design & development] +1 (940) 343-5183  

Webshop Blog

1

Understanding Variable Scope

I’m going to deviate from the PHP From the Top series I’ve been writing from time to time to address a few other programming/scripting concepts. Today we’ll be discussing variable scope, what it is, and how to use it. If you have been following along with the PHP From the Top Series, some of this may be over your head at this point, and that’s okay. If you have questions, feel free to ask them in the comments. We will cover these concepts again later in the series. Much of this article will apply to many different languages; however, I will be using PHP to illustrate these concepts in this article.

What is Variable Scope

Variable scope refers to the context in which a variable is defined or the setting in which it is available for use. Whenever a variable is declared, it is declared in a particular scope. In PHP, there are two different possible scopes, global and local.

When you declare a variable in PHP like this:

	$count = 5; //$count is defined in the global scope

The variable is declared in the global scope. This means that the variable is available to interact with and be used and manipulated by other processes in the global scope. Variables declared in the global scope cannot be used in the local scope and the other way around. Let’s look at what it means to define something in the local scope.

function full_name($first_name, $last_name) {

	$full_name = $first_name.$last_name;

	return($full_name); //$full_name is declared in the local scope
}

Determining Which Scope You’re Using

Variables that are defined in the local scope cannot interact with variables in the global scope. You could even have two variables of the same name, in either scope and they could hold two different values. For example:

function do_something() {

	$variable = 2; //local scope

}

$variable = 5; //global scope

echo $variable; //echoes 5

do_something();

echo $variable; //still echoes 5

Within the function do_something(), the value of $variable was set to 2. However, it was set in the local scope. The echo statement, however, was used in the global scope. Therefore, the instance of $variable that was set to 2 was never accessed or used. Essentially, when a variable is defined within a function, that variable only exists within that function. Once the function is executed and completed, the variable is no longer accessible and cannot be used.

Working Around Variable Scope

So if we can’t access a global variable inside a function how to we get access to those values? Well there are a couple of ways to do this. The first way is to pass variables into functions as arguments. Passing a global variable as an argument allows the variables value to be altered in the local scope by effectively making a copy of the variable and pasting it into the new scope. But will the value still be altered in the global scope? No it won’t. This is because we are only creating a copy of the variable. However, we can still retrieve the new value by returning the variable when we are done. Let’s look at an example:


$var = 40;

function divide_by_two($var) {
	return($var / 2);
}

echo $var; //echoes 40

$var = divide_by_two($var);

echo $var; //echoes 20

This method, however, can get to be a bit cumbersome when working with large amounts of variables. Passing in all of these variables as arguments can get messy, and PHP functions can only return one variable at a time. You would therefore need to call functions multiple times. Is there an easier way? Yes there is. We can use the global keyword to bring global variables into the local scope. Say you have a variable that stores a path to a upload folder for your application.


$upload_path = '/path/to/uploads/directory/';

function delete_uploaded_file($filename) {

	//bring the variable $var out of the global scope and into
	//the local scope so it can be accessed and altered.

	global $upload_path;

	if(file_exists($upload_path.$filename)) {
		unlink($upload_path.$filename);
	}
}

delete_uploaded_file('image.jpg');

This can also be done by using the superglobal associative array $GLOBALS:


$upload_path = '/path/to/uploads/directory/';

function delete_uploaded_file($filename) {

	if(file_exists($GLOBALS['upload_path'].$filename)) {
		unlink($GLOBALS['upload_path'].$filename);
	}
}

delete_uploaded_file('image.jpg');

Using Static Variables

Static variables can occasionally come in handy as well, and are a good thing to know about when the need comes up. A static variable only exists in the local scope. However, the value of the variable remains there even when the parser leaves the local scope.

	function show_last_count() {
		//$count is declared as static and the value will remain after the function as been called.
		static $count = 0;
		echo $count;
		$count++;
	}
	show_last_count(); //echos 0
	show_last_count(); //echos 1
	show_last_count(); //echos 2
	show_last_count(); //echos 3

NOTE: when assigning values to static variables you must assign them as listed in the example above–that is as a straight value, not as the result of an expression. Assigning the result of an expression as static will throw in a parse error.

	function do_something() {
		static $static_var = 1 + 1; //throws a parse error.
	}

Conclusion

Understanding scope is a crucial concept in programming, and lack of understanding it can lead to writing some incredibly messy and difficult to maintain code. However, that doesn’t mean that you should always use the methods defined here. I’ve listed a few options for you, use the one that makes the most sense to you. If it makes sense to pass a variable into a function as an argument, perhaps because that value is constantly changing, do it that way. It is okay to work within where you’re comfortable. But that doesn’t mean you shouldn’t be aware of what your other options are.

If you have any questions, if I didn’t explain something as clear as you would have liked, please don’t hesitate to let me know. Leave a comment on this article. Someone will be thrilled to help you out.

 

Leave a Response

Use the <code> tag for code.

 

One Response to “Understanding Variable Scope”

  1. Understanding scope is a crucial concept in programming, and lack of understanding it can lead to writing some incredibly messy and difficult to maintain code. However, that doesn’t mean that you should always use the methods defined here. I’ve listed a few options for you, use the one that makes the most sense to you. If it makes sense to pass a variable into a function as an argument, perhaps because that value is constantly changing, do it that way. It is okay to work within where you’re comfortable. But that doesn’t mean you shouldn’t be aware of what your other options are.

    If you have any questions, if I didn’t explain something as clear as you would have liked, please don’t hesitate to let me know. Leave a comment on this article. Someone will be thrilled to help you out.