Understanding Variable Scope in PHP

Variables are an important part of any programming language. You can use them to store all kinds of information like integers, floats, strings, arrays, the contents of a file, etc. The data stored in variables can then be manipulated by adding or removing information. Using variables also allows us to create loops and perform some tasks repetitively. You can also define functions that take different variables as arguments and give back new data.

In this tutorial, we’ll learn about an important concept called variable scope and how it affects the way you write code in PHP. We’ll also cover the usage of the global and static keywords.

What Is Variable Scope?

Variables are used to store and access or manipulate information later, but you cannot just access their data from any place you like. Some variables might become inaccessible in certain places, depending on the programming language you are using.

In simple terms, the scope of a variable determines its availability in different sections of a program.

Variable Scope in PHP

PHP has an easy-to-understand and beginner-friendly approach to variable scope.

Basically, a variable you define somewhere in a PHP file will be visible or available almost everywhere after it is defined. You will also be able to use it within other files added to the program using include() and require().

Let’s say there is a file called variables.php and it contains the following code:

The variable $apple_count will also be available in another file with the following code:

However, this variable will not be available inside user-defined functions. Here is an example:

So variables defined outside a user-defined function are not available within the function. Similarly, variables defined within a function exist just inside that function. That’s why we get a notice when we try to echo the value of $mango_count outside our fruit_count() function.

Access Variables Inside Functions

Functions usually require some input data to do something useful. The best way to do that is to pass the information along using different parameters in function definition. For example, the natural_sum() function below takes the number of natural numbers as its parameter.

If you need to take a variable from the outside and use it inside a function, you can consider using the global keyword.

Using the PHP global Keyword to Access Variables

You can simply use the keyword global before any variable to get its value from the global scope. When you do that, whatever is stored in the variable will be available inside the function without passing it as a parameter. You will also be able to change the value of the variable inside the function, and the changes will be reflected everywhere.

Here is an example that rewrites the natural_sum() function to use a global value of $n.

One of the major disadvantages of doing things this way is that we no longer know what kind of data natural_sum() relies on to generate its output. The value of $n can also be changed anywhere in your code, and it will affect the output of calling natural_sum() again.

In the above example, we have no way of knowing what changed the output of natural_sum() without looking at the code. We can still easily figure out here that the value of $n was incremented by 5 within the function itself. However, this might not be so easy when you are dealing with a large amount of code.

That’s why it’s better to avoid using globals whenever possible.

Using the PHP $GLOBALS Superglobal to Access Variables

Another way to access global variables inside a function is to use the $GLOBALS superglobal. This also allows you to have a local variable with the same name as the global variable.

The problems that make using the global keyword a bad practice also exist for $GLOBALS as well.

You should consider avoiding the use of global variables as much as possible and only use them if you can’t think of any other way to easily get the data from a variable inside your particular function.

One situation where it might be helpful to use global is when you want to track and update the value of a variable across several different function definitions and want the changes in the variable’s value to be reflected everywhere.

Static Variables in PHP

Variables defined inside a function in PHP only exist within the scope of that function. This means that the variable is no longer available once we exit the local scope. It also means that any value we assign to a variable inside a function will not persist across multiple calls to that function.

As you can see, we call natural_sum() three times in the above example, but its value keeps resetting to 0 at the top of our calls. This makes it hard for us to keep track of the number of times we called natural_sum().

One way to get around this limitation is to use the static keyword. Now, the value of $count will persist across multiple calls, as shown by the example below.

The example above also shows that declaring a variable to be static in PHP does not make it available outside its scope.

If you want to access the value of a variable outside its function, the best way to do so is by using a return statement. You can return any type of value like strings, arrays, objects, etc.

Final Thoughts

PHP has two kinds of scopes for variables. There’s a general global scope, where variables you define in the program are available in all places, like loops and other files which include the file with variables. Then there is a local scope for user-defined functions, in which the variables are restricted to that particular function.

However, this does not prevent free movement of information inside and outside the functions. You can get access to outside variables that are not included as parameters in the function by using the global keyword. Similarly, you can access the value of a variable defined inside a function by using a return statement.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.