Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 147 ยท Functions

Variable Scope

Understand PHP variable scope - why functions can't see outside variables, the global keyword and $GLOBALS, static variables that remember values, and why globals hurt.

A variable's scope is the part of the program where its name means something. PHP's rule is simpler and stricter than in many languages: a function can only see its own variables. A variable you create at the top of a script is invisible inside a function, and a variable created inside a function disappears when the function returns.

That surprises developers coming from JavaScript or Python, where inner code can read outer variables. In PHP, it's a feature: a function's behavior depends only on its arguments, which makes it predictable and easy to test. This lesson explains local and global scope, the global keyword and $GLOBALS (and why to avoid them), static variables, and how scope works in included files and closures.

Local scope

Every function call gets a fresh, private set of variables: its parameters plus anything it assigns. Nothing from the outside leaks in, and nothing leaks out.

PHP Functions can't see outside variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
Title: (not visible here)
Outside: Code Garden
pageViews outside: (not visible here)

Inside showTitle(), $siteName simply doesn't exist, and $pageViews is gone as soon as the function returns. The ?? operator hides the problem here. Without it, PHP reports a warning and uses null:

PHP The undefined variable warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example shows the warning on purpose:

TEXT
Warning: Undefined variable $taxRate in main.php on line 6
50

The function used null for $taxRate, so 1 + null is 1 and the "taxed" price is wrong without any crash. Read undefined-variable warnings as bugs. The fix is to pass the value in:

PHP
function priceWithTax(float $price, float $taxRate): float
{
    return $price * (1 + $taxRate);
}

echo priceWithTax(50, $taxRate); // 60

Same name, different variables

Because each function has its own scope, two functions can use the same variable names without any conflict, and a recursive function gets a fresh copy of its variables on every call (see Recursion).

PHP Each call has its own variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 3 2 1, ABCD and outer i / outer result. Both functions used $i and $result, and neither touched the script's own $i and $result.

Blocks like if, for and foreach do not create a new scope in PHP. A variable assigned inside a loop is still visible after the loop, in the same function or script. Only functions (and files included from inside functions, see below) draw scope boundaries.

Global scope

Variables created outside any function live in the global scope. The script's top level, and any file included at the top level, share it. There are two ways for a function to reach into it, and both are best avoided in new code.

The global keyword

global $name; inside a function binds a local name to the global variable of the same name:

PHP global imports a global variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints Visits: 3. global $visitCount; actually creates a local reference to the global variable, so changes go straight through.

The $GLOBALS array

$GLOBALS is a superglobal: an array available everywhere that holds every global variable by name.

PHP
function currentVisits(): int
{
    return $GLOBALS['visitCount'];
}

Since PHP 8.1, $GLOBALS is a read-only copy as a whole: you can still read and write individual entries ($GLOBALS['visitCount']++ works), but you can no longer replace the whole array ($GLOBALS = [] is a compile-time error) or pass it by reference.

Why globals hurt

Code like registerVisit() looks harmless in a ten-line script. In a real application, globals cause real problems:

  • Hidden inputs. The signature registerVisit(): void doesn't say it depends on $visitCount. Readers have to inspect the body to know.
  • Action at a distance. Any function anywhere can change a global, so when its value is wrong you have to search the whole codebase.
  • Name collisions. Two libraries that both use a global $config silently overwrite each other.
  • Hard to test. A test must set up the right global state first, and leftover state leaks into the next test.

The alternative is almost always to pass values in as arguments and return results:

PHP Replacing a global with parameters and return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Now each function's inputs are visible at the call, it can be tested with any number, and nothing else can interfere. This prints Visits: 3 and After 99: 100. When many functions need the same shared state, such as a database connection or configuration, the answer is an object that holds it, passed to whatever needs it. That's called dependency injection, and you'll meet it in OOP Design Principles.

static variables

A static variable is local to a function, so no other code can see it, but it keeps its value between calls. It's initialized only the first time the function runs:

PHP static variables remember values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints T-001, T-002 and T-003. A normal $number = 0; would reset to zero on every call and always produce T-001.

A classic use is memoization: caching results of an expensive calculation so repeated calls are instant.

PHP Caching results in a static array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the second call for 12 reusing the cache:

TEXT
  (computed so far: 1)
144
  (computed so far: 1)
144
  (computed so far: 2)
25

Some details worth knowing:

  • Since PHP 8.3, the initializer can be any expression, such as static $start = microtime(true);. Before 8.3 it had to be a constant expression like 0 or [].
  • A static variable lives for the whole request (or CLI run). On a web server, each new request starts fresh, so it's no replacement for a database or cache across requests.
  • Static variables are still hidden state. For anything bigger than a small cache or counter, an object with a property is clearer and easier to reset in tests.

Scope and included files

When you include or require a file, its code runs in the scope where the include statement is. Included at the top level, the file's variables become globals. Included inside a function, they're local to that function. This is how simple template systems pass data to a view: the variables of the rendering function become visible in the template. You'll build one in PHP and HTML Templates.

Scope and closures

Anonymous functions follow the same rule: they don't see outer variables automatically. You import variables explicitly with use:

PHP
$discount = 0.1;

$applyDiscount = function (float $price) use ($discount): float {
    return $price * (1 - $discount);
};

Arrow functions (fn) are the one exception: they capture outer variables automatically, by value. Both are covered in the next lesson, Anonymous Functions and Closures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does this print? $x = 5; function show() { echo $x ?? "none"; } show();

    Functions can't see global variables. $x is undefined inside show(), so the ?? operator falls back to "none".
  2. 2. Which kind of block creates a new variable scope in PHP?

    Only functions create a scope. Variables assigned inside loops and if blocks remain visible afterward in the same function or script.
  3. 3. A function contains static $n = 0; $n++; return $n;. What does the third call return?

    The static variable is initialized once and keeps its value between calls, so the calls return 1, 2 and 3.
  4. 4. Why is passing a value as an argument usually better than using global?

    Globals are hidden inputs that any code can change. Parameters make a function's dependencies explicit and its behavior predictable.

Summary

  • Each function has its own local scope: it sees only its parameters and the variables it creates, which vanish when it returns.
  • Top-level variables live in the global scope, invisible inside functions. Reading one there gives an "Undefined variable" warning and null.
  • if and loop blocks don't create scopes; only functions do.
  • global $x; and $GLOBALS['x'] reach global variables, but hide dependencies and make code hard to test. Pass arguments and return values instead.
  • static $x = 0; keeps a local value between calls, useful for counters and caches. Arbitrary initializer expressions arrived in PHP 8.3.
  • Included files run in the scope of the include statement; closures import variables with use, while arrow functions capture them automatically.

Next: Anonymous Functions and Closures