PHP Tutorials

Scope

Scope refers to the lifetime of any particular variable. Variables are available only in certain areas of a program, depending on where they are declared. The main scope, known as the global scope, contains most of the variables you declare. So far, all of the variables we’ve declared have belonged to the global scope. Later, when we get to functions, the global scope will contain fewer of your variables.

Other parts of your program have their own scopes. The main reason behind this is to prevent the accidental changing of a variable. For example, in any given program, you might create a variable called $temp. A variable like this might be used while you perform some kind of processing algorithm.

However, what if, in the course of that processing somewhere, the value of $temp was changed by code located in some other function or even in some other file? For example, look at the following code:



// Code segment – NOT a working example
$temp = "This string is being processed.";

for ($x = 1; $x <= strlen($temp); $x++)
{
$part = substr($temp, $x, 1);
doSomething($part);
}

Don’t worry about trying to figure out exactly what the code does. It doesn’t really have much use, as it is; doSomething() undefined. Either way, there’s only one place where it appears $temp is being assigned a value—at the very beginning of the segment. And luckily, that’s the way it is. Without variable scope, though, doSomething() could’ve had an assignment to $temp in it and we would never know. Finding a bug in code without a variable scope can take weeks of persistent debugging time by an experienced programmer or even a team of experienced programmers.

Variable scope is basically divided between the global scope and individual functions; each (the global scope and each function) has a scope of its own, and, thus, no variables will be overwritten by a function or segment of code that isn’t supposed to do so.

Functions

Class member functions

Filed under: Chapter 2 @ 10:24 pm

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress