• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Functions / PHP Variable Scope: All You Need to Know

PHP Variable Scope: All You Need to Know

15 October 2010 / 6 Comments

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! 🙂




Filed Under: PHP Functions Tagged With: functions, global, local, php, static variables, superglobals, variable scope

Reader Interactions

Comments

  1. rhfarukh says

    5 July 2011 at 3:51 am

    I really loved this post. As I was confused a little bit about global and local variables. Thanks a Lot.

    Reply
  2. Mamta Rana says

    21 March 2012 at 4:59 am

    Really It is very useful..
    Now I can understand what is the difference between global and super global.

    Reply
  3. anupy says

    19 May 2013 at 8:11 am

    Basically, I understood the use of static member. The way you explained that’s just great!! Thanks.

    Reply
  4. Constantine says

    16 September 2019 at 8:10 am

    Thank you so much for this clear explanaition!

    Reply
  5. Dale says

    26 November 2019 at 3:34 am

    I am finding that within a function, I cannot change the value of a global variable on the same line (ie global $var = ‘new value’; ). I have to declare the variable as global before I can use it which surprises me. It seems a bit inefficient…

    Reply
    • Matt Doyle says

      3 December 2019 at 10:35 am

      Yep, that’s just how PHP works unfortunately!

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits