Variable Scope In PHP – Very Simple Examples

Welcome to a quick tutorial on PHP variable scope. So you may have defined a variable inside a function, and it “mysteriously disappeared” afterward? Well, rest assured that it is not a PHP bug, nor has it been abducted by aliens.

Variable scope is simply the boundaries of where a variable exists. In PHP, there are 4 categories of variable scope:

  1. Local – Variables that are defined within functions, only exist inside the function itself.
  2. Global – Variables that are defined outside of functions, only exist outside of functions. Although they can be “adopted” into functions by specifying global $VAR.
  3. Static – Local variables that retain their values.
  4. Function – Used to pass values into functions, also known as “parameters”.

That covers the basics, but just how does variable scope work? Read on for the examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Scope Examples Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

VARIABLE SCOPE EXAMPLES

All right, let us now get started with the examples of variable scope in PHP.

 

1) LOCAL VARIABLES

1-local.php
<?php
// (A) SUM FUNCTION
function sum () {
  $first = 123;
  $second = 456;
  return $first + $second;
}

// (B) CALL THE SUM FUNCTION
$result = sum();
echo $result; // 579

// (C) $FIRST + $SECOND ARE GONE!
echo $first;
echo $second;

Local variables are pretty much self-explanatory. In this example, we have $first and $second inside function sum(). These two variables will only exist inside of sum(), and they perish once the function is done with the calculations.

 

2A) GLOBAL VARIABLES

2a-global.php
<?php
// (A) GLOBAL VARIABLE
$name = "Jon Doe";

// (B) DUMMY FUNCTION
function intro () {
  // (B1) THIS WILL THROW A "UNDEFINED $NAME" WARNING
  $str = "Hi! My name is ";
  echo $str . $name; 

  // (B2) USE GLOBAL $NAME - NO LONGER THROWS WARNING
  global $name;
  echo $str . $name; 
}
intro();

Global variables are pretty much “whatever variables that are defined outside functions”. Yep, global variables pretty much exist only outside of functions, although we can “adopt” them into functions using global.

 

 

2B) SUPERGLOBALS

2b-superglobal.php
<?php
function demo () {
  print_r($_POST);
  print_r($_GET);
  print_r($_FILES);
  print_r($_SERVER);
}
demo();

Next, please take note that PHP has a bunch of what is known as the “superglobals”. These variables are pretty much “system-related data” and exist everywhere – Both inside and outside of functions.

 

3) STATIC VARIABLES

3-static.php
<?php
// (A) NON-STATIC - VALUE RESETS
function nostatic () {
  $count = 0;
  $count++;
  echo $count . "<br>";
}
echo nostatic(); // 1
echo nostatic(); // 1

// (B) STATIC - RETAINS VALUE
function isstatic () {
  static $count = 0;
  $count++;
  echo $count . "<br>";
}
echo isstatic(); // 1
echo isstatic(); // 2
echo isstatic(); // 3
echo $count; // STATIC VARIABLES ARE STILL LOCAL

Remember from 1 minute ago that local variables will perish once the function is done processing? Yep, static variables are interesting ones that will retain their values. But take note – They are still local variables and only exist inside the function.

 

 

4) FUNCTION PARAMETERS

3-parameters.php
<?php
// (A) DUMMY FUNCTION
function intro ($name) {
  echo "My name is $name.";
}
 
// (B) CALL FUNCTION
intro("Jon");
intro("Joy");

You guys should already know this… Parameters are what we use to pass values into functions. But this is kind of subjective, as some people consider them to be local variables (not “standalone parameter scope”).

 

5) SCOPE FOR INCLUDED FILES

5a-include.php
<?php
$name = "Jon";
5b-include.php
<?php
// (A) $NAME WILL BE GLOBAL
include "5a-include.php";
echo $name;

// (B) DUMMY FUNCTION
function intro () {
  global $name;
  echo $name;
}
intro();
5c-include.php
<?php
// (A) $NAME WILL BE LOCAL
function intro () {
  include "5a-include.php";
  echo $name;
}
intro();
 
// (B) $NAME DOES NOT EXIST
echo $name;

As a final example, take extra note of how variables inside included files act – If the file is included in the global space, the variable will be global scope. If the file is included inside a function, the variable will be local scope. That simple.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) WHY VARIABLE SCOPE EXISTS

Why is there a need for variable scope? Isn’t it better and less confusing to keep all variables as superglobals? Well, the answer is simple – Performance and memory management. Keeping all variables, including all sorts of temporary ones, is just going to waste a lot of system resources.

 

INFOGRAPHIC CHEAT SHEET

PHP Variable Scope (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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