Scope is defined, within the realms of PHP, to mean the context within which a variable, or a function is defined. For the most part, any variable defined within the flow of a program is available throughout the rest of that program, or within the global scope of the program. There are a few cases where scope changes though, and one of these is when entering a function definition.
You can think of functions as self-contained sections of code, and while writing a function, you don’t need to worry about what might be happening outside the function definition, you can concentrate on its inner workings. Every function has its own scope inside which, variables are “hidden from the outside world”, and vice-versa.
More precisely, any variables which you declare within the function will not be available from outwith the function. So, the following code
function my_function(){ $a = 5; } echo $a;
produces
That’s right, nothing! (PHP by default treats undefined variables as if they are null, or blank) This also happens in reverse. Let’s try referencing a variable created outside a function from inside the function
$b = 20; function my_function(){ echo $b; $b = 10; echo $b; } my_function();
produces
10
Here, we only see the value of $b that was created inside the function. From the function’s point of view, when we reference $b in line 3, it doesn’t exist. We can fix this by use of the global keyword
$b = 20; //defined in the "global scope" function my_function(){ global $b; echo $b; $b = 10; //assigns $b = 10 _in the global scope_ echo $b; } my_function(); echo $b;
produces
20 10 10
Here, the use of “global” tells the function to use the version of $b that has been defined globally, that is, the version that has been defined outside the function but within the same scope as the function definition.
You might wonder though, why the value of $b in line 9 is printed as “10″. That’s because, by defining $b as global within the function, we are telling the function to treat any expression assigning $b a value (such as “$b = 10″ on line 5) to be working with the global variable $b, and not a local variable.




