While we have covered the basics in how to use variables within PHP there’s still a whole other side to variables we haven’t discussed yet. This includes understanding variable scope, along with the proper use of global and static variables. We’ll start off with variable scope.
The scope of a variable, simply referred to as the variable scope, is the context within which it is defined. Basically if a variable is defined in one scope, you cannot access that same variable within a different scope. To better understand what I mean let’s take a look at the following example code:
The above code won’t produce any output, or it will produce an error message depending on your php.ni settings. This is because as far as PHP is concerned there is no $a variable to output when asked. But the $a variable is set, right there, in the first line of the script right?
Technically yes that variable is set and if you tell PHP to echo that variable within the same environment it was set in – it will. However once you try to call that variable somewhere else, such as within a separate function, PHP considers that a separate scope and as such the variable won’t be displayed.
PHP variables can be in three different scopes:
- Global
- Local
- Static
A variable declared outside a function has a global scope and can only be accessed outside a function.
A variable declared inside a function has a local scope and can only be accessed within that specific function and is deleted once the function has been run.
A local scope variable that needs to keep it’s value in the event that the same function runs repeatedly is set to the static scope.
So let’s take a look at the following code example first just to get a better grasp of how PHP will assign variable scopes.
Global Variables
Now let’s say we want to make our original code work. This one:
We would need to make the original $a variable, which is in the global scope, available inside our local scope of the test();
function. To do this we need to use the global
keyword before the variables (inside the function):
Local Variables
However if we only need $a
for just the test();
function then there’s no reason to set it within the global scope. We can then simply set it within the local scope and still get our result.
Static Variables
Now say that we want to add 1 to our original number every single time we run our function – and we want to run it 5 times. Initially some of you would probably try the following:
Unfortunately this would produce 11111 because the function runs as new every single time and any variables set within the local scope are deleted after the function has run. So how do we tell PHP to remember the value of our $a
variable? We set $a
as a static variable.
Now we get our desired result of 12345 and $a
maintains its value as we call test();
more and more.
Leave a comment