17May/100
Zooming in on PHP Variable Scope
Variables within php have a property that is called "scope". Scope refers to places within your php script that you can use your variable, and where you cannot.
Within PHP there are four specific types of scope.
- SuperGlobal Scope
- This type of scope are available everywhere within your scripts.
- Global Scope
- This type of scope are visible throughout your script however they are not visible inside of a function (this can be overcome by using Function Global Scope)
- Function Scope
- This type of scope relates to variables created within functions. Meaning that any variable created within a function is only visible to your script within the function.
- Function Global Scope
- This type of scope relates to variables created outside of your functions. If you declare a variable inside your function as "global", this "global" variable is not global to your entire script, however this definition of "global" inside of a function points to the value of a variable outside of your function that has been defined as global as previously defined. you would tend to think that defining a variable "global" inside of a function would make that variable available to your entire script, however this is wrong. this definition points your local function variable to the counterparts value defined outside your function (example follows)
<?php //define a variable outside of our function $var_two = 2; //global scope, meaning it is global to your current script function your_function($variable_one) { $var = "one"; $var_two = 4; //function scope variable, local to inside the function only $var_three = global $var_two //$var_two is equivalent to "2" set outside the function //$var_three is now set to "2" } ?>