Variable scopes in PHP

As we already had a very brief and sweet introduction to PHP, we will now check out the different variable scopes in PHP.

So there are basically three variable scopes in PHP, which are:

  1. Local – Any variable declared within a function.
  2. Static – Any local variable that can live out of it’s scope. Similar to local variables, static variable too can only be used within a function.
  3. Global – Any variable that can be accessed from anywhere.

Let’s check out the below PHP code first and later we can go with further explanation on the variable scopes.

When we execute the above PHP code on the server, we get an output as:

PHP Variable ScopesTry to understand each and every line of the PHP code and it’s output above.

Below are few important points to note:

Local variable scope is only within a function, which means they can be declared and accessed within the same function. Therefore as soon as the function execution ends, all it’s local variables get destroyed and are no more accessible.

Static variables are similar to local variables, except that static variables hold the values even after the function execution gets completed, which means they are not destroyed after the function execution completes. This can be clearly understood from the above code snippet, where we are calling the testGlobalAndStatic function twice one after the other.

testGlobalAndStatic() – Call 1

In the function testGlobalAndStatic , there is a local variable a (=99) and a static variable b (=99). Both are then incremented by 1 and their value is printed (a=100 and b=100). This seems to be as expected.

testGlobalAndStatic() – Call 2

When the function testGlobalAndStatic is called again, note that the value of static variable b remains the same as that for the previous method call i.e. 100, since it never got destroyed after the first call to testGlobalAndStatic function completed and still holds the updated value, whereas the local variable a has to initialize itself again to 99, since it’s updated value got destroyed after the previous call to testGlobalAndStatic function completed. So the value of a gets re-initialized to 99 while value of b being static stays to 100.

Global variables in turn can be accessed from anywhere in the PHP application, and it always holds the updated value based on the modifications done to it by various different functions, which means that if a function 1 modifies a global variable to 2, another function 2 modifies it to 5, then the function 3 accessing the same global variable will get the value as 5.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.