PHP Variable Scope: All You Need to Know

Discover how variable scope works in PHP. This beginner tutorial explores global and local scope, and shows how to access globals within functions, work with superglobals, and create static variables.

PHP Variable Scope: All You Need to Know

When you're just starting to work with functions and objects in PHP, variable scope can be the cause of some confusion. Fortunately, PHP's scope rules are relatively easy to understand (compared to some other languages, at least!).

In this tutorial you'll learn all you need to know about variable scope in PHP. You'll look at:

  • The concept of variable scope — what it is, and what it means
  • The differences between global and local scope
  • How to access global variables from within a function
  • PHP's superglobals, and how they work
  • How to use static variables to preserve state

Let's get started!

What is variable scope, anyway?

The scope of a variable in PHP is the context in which the variable was created, and in which it can be accessed. Essentially, PHP has 2 scopes:

Global
The variable is accessible from anywhere in the script
Local
The variable is only accessible from within the function (or method) that created it

Variable scope — and, in particular, local scope — make your code easier to manage. If all your variables are global, they can be read and changed from anywhere in your script. This can cause chaos in large scripts as many different parts of the script attempt to work with the same variable. By restricting a variable to local scope, you limit the amount of code that can access that variable, making your code more robust, more modular, and easier to debug.

Here's a simple example that shows how global and local variables work:


<?php
 
$globalName = "Zoe";

function sayHello() {
  $localName = "Harry";
  echo "Hello, $localName!<br>";
}

sayHello();
echo "The value of \$globalName is: '$globalName'<br>";
echo "The value of \$localName is: '$localName'<br>";

?>

This script displays the following:


Hello, Harry!
The value of $globalName is: 'Zoe'
The value of $localName is: ''

In this script, we create 2 variables:

  • $globalName is a global variable since it's not created inside any function.
  • $localName is a local variable, created and used inside the function sayHello().

After creating the global variable and the function, the script calls sayHello(), which displays 'Hello, Harry!'. The script then attempts to display the values of the 2 variables by using echo. Here's what happens:

  • Since $globalName was created outside the function, it is accessible from anywhere in the script — including this point — so its value, 'Zoe', is displayed.
  • $localName, on the other hand, is only accessible from within the sayHello() function. Since the echo statement is outside the function, PHP won't let the code access this local variable. Instead, PHP assumes that the code wants to create a new global variable called $localName, which it sets to the default value of an empty string. This is why the second call to echo displays the value of $localName as ''.

Accessing global variables from within functions

Globe

As I mentioned above, you can read and change a global variable's value from anywhere in your script.

To access a global variable from outside a function, just write the variable's name. To access a global variable from within a function, however, you first need to declare the variable as global within the function by using the global keyword:


function myFunction() {
  global $globalVariable;
  // Access the variable as $globalVariable
}

If you don't do this then PHP assumes you're trying to create or use a local variable.

Here's an example script with a function that accesses a global variable:


<?php

$globalName = "Zoe";

function sayHello() {
  $localName = "Harry";
  echo "Hello, $localName!<br>";

  global $globalName;
  echo "Hello, $globalName!<br>";
}

sayHello();

?>

This script produces the following output:


Hello, Harry!
Hello, Zoe!

The sayHello() function uses the global keyword to declare the $globalName variable as global. It can then access the variable and display its contents ('Zoe').

Superglobals explained

Superman

PHP provides a special set of predefined global arrays containing various useful nuggets of information. These arrays are known as superglobals because they're accessible from anywhere in your script — including inside functions — and you don't need to declare them as global using the global keyword.

Here's a full list of the superglobals available in PHP, as of version 5.3:

$GLOBALS
Contains a list of all global variables in the script (excluding superglobals)
$_GET
Holds a list of all form fields sent by the browser using the GET request
$_POST
Holds a list of all form fields sent by the browser using the POST request
$_COOKIE
Holds a list of all cookies sent by the browser
$_REQUEST
Contains all the keys and values in the $_GET, $_POST and $_COOKIE arrays combined
$_FILES
Holds a list of any files uploaded by the browser
$_SESSION
Allows you to store and retrieve persistent session variables for the current browser
$_SERVER
Holds server environment info such as the filename of the running script, and the IP address of the browser.
$_ENV
Contains a list of environment variables passed to PHP. These can include variables provided by the shell, as well as CGI variables.

For example, we can use the $_GET superglobal to retrieve a value included in the query string of the script's URL, and display the value in the page:


<?php

$yourName = $_GET['yourName'];
echo "Hello, $yourName!";

?>

If you run the above script using a URL along the lines of http://www.example.com/script.php?yourName=Fred then the script displays:


Hello, Fred!

Warning: In a real-world script, you should never send user input directly to the browser like this. It's a security risk. Always check or filter the input first.

The $GLOBALS superglobal is handy because it lets you access global variables within functions without needing to use the global keyword. For example:


<?php

$globalName = "Zoe";

function sayHello() {
  echo "Hello, " . $GLOBALS['globalName'] . "!<br>";
}

sayHello();  // Displays "Hello, Zoe!"

?>

Find out more about superglobals on the PHP website.

Static variables: Variables that like to stick around

Pot of glue

When you create a local variable inside a function, that variable only hangs around while the function is being run. As soon as the function exits, the local variable vanishes. When the function is called again, a new local variable is created.

Mostly this is a good thing. It ensures that your functions are self-contained, and that they work the same way each time they're called.

However, there are situations where it's handy to create a local variable that remembers its value between one call to the function and the next call. This is exactly how static variables work.

To create a static variable in a function, you write the keyword static followed by the variable name, and give the variable an initial value. For example:


function myFunction() {
  static $myVariable = 0;
}

Let's look at a situation where static variables are useful. Say you've written a function that creates widgets, and returns the number of widgets created so far. You might try doing this using a local variable:


<?php

function createWidget() {
  $numWidgets = 0;
  return ++$numWidgets;
}

echo "Creating some widgets...<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";

?>

However, since $numWidgets is recreated each time the function is called, it doesn't produce the desired result:


Creating some widgets...
1 created so far.
1 created so far.
1 created so far.

By making the variable static, we can get it to stick around from one function call to the next, preserving its value:


<?php

function createWidget() {
  static $numWidgets = 0;
  return ++$numWidgets;
}

echo "Creating some widgets...<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";

?>

The script now displays the expected output:


Creating some widgets...
1 created so far.
2 created so far.
3 created so far.

While static variables remember their values across function calls, they only last as long as the running script. Once the script exits, a static variable gets destroyed, just like local and global variables do.

Summary

In this tutorial we've looked at the concept of variable scope in PHP. We explored local and global scope; learned how to access global variables in a function; touched on PHP superglobals; and used static variables to preserve variable values between function calls.

I hope you found the article useful. As always, I'd love to hear your feedback in the comments below.

Happy coding! :)

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

3 responses (oldest first):

05-Jul-11 03:51
I really loved this post. As I was confused a little bit about global and local variables. Thanks a Lot.
21-Mar-12 04:59
Really It is very useful..
Now I can understand what is the difference between global and super global.
19-May-13 08:11
Basically, I understood the use of static member. The way you explained that's just great!! Thanks.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page