Introduction
Where can a variable be used? The answer is called its scope. PHP is strict about it: a function cannot see the variables outside it, and the outside cannot see the variables inside. This protects your code from accidental changes, but it also surprises beginners who come from other languages. In this lesson you will learn the rules of scope, how to share values in a safe way, and how closures and arrow functions let a small function remember the values around it.
How it works
A variable created outside every function lives in the global scope. A variable created inside a function is local: it exists only while the function runs, and it disappears after that. Even if a global variable and a local variable have the same name, they are two separate variables. Reading a global variable inside a function without permission gives an undefined variable warning.
There are three ways to bring a value in. The best way is to pass it as a parameter. The keyword global $counter; inside a function links the name to the global variable, and the $GLOBALS array does the same. Both make code hard to test, so use them rarely.
A static variable is a local variable that keeps its value between calls. In static $calls = 0;, the assignment happens only the first time. After that, the variable remembers the last value, which is useful for counters and caches.
A closure is a function without a name, which you can store in a variable, pass to another function or return. Write it with the keyword function. A closure does not see the variables around it unless you list them with use:
$add = function ($x) use (&$total) { $total += $x; };
Without the ampersand, use ($rate) copies the value at the moment the closure is created. With &, the closure shares the variable and can change it. A closure that remembers variables is how you build a counter generator: each call to makeCounter() creates its own private $count.
An arrow function is a short closure for one expression: fn($x) => $x * $rate. It captures the variables of the outer scope automatically, by value, so you do not need use. It can only contain a single expression, and the result is returned.
Closures are the key for functions such as array_map, array_filter, usort and array_reduce, which take another function as an argument. The type callable accepts any function value, and Closure is the class of closures.
Example
<?php
$counter = 10;
function noAccess()
{
return isset($counter) ? "sees it" : "cannot see it";
}
echo noAccess(), "\n";
function withGlobal()
{
global $counter;
$counter++;
}
withGlobal();
echo $counter, "\n";
function counterNext()
{
static $calls = 0;
$calls++;
return $calls;
}
counterNext();
counterNext();
echo counterNext(), "\n";
$rate = 3;
$triple = fn($x) => $x * $rate;
echo $triple(5), "\n";
$total = 0;
$add = function ($x) use (&$total) {
$total += $x;
};
$add(5);
$add(7);
echo $total, "\n";
function makeCounter(): callable
{
$count = 0;
return function () use (&$count) {
return ++$count;
};
}
$c1 = makeCounter();
$c2 = makeCounter();
echo $c1(), $c1(), $c1(), " ", $c2(), "\n";
function multiplier(int $m): Closure
{
return fn($x) => $x * $m;
}
$double = multiplier(2);
echo implode(",", array_map($double, [1, 2, 3])), "\n";
echo implode(",", array_filter([1, 2, 3, 4, 5, 6], fn($n) => $n % 2 == 0)), "\n";Line by line
noAccesscannot see the global$counter, soissetis false.withGlobalusesglobalto change the outside variable from 10 to 11.counterNextkeeps$callsbetween calls withstatic, so three calls give 3.- The arrow function
$triplecaptures$rateautomatically. - The closure
$adduses&$total, so it changes the outer total from 0 to 12. makeCounterreturns a closure.$c1and$c2each have their own count.multiplierreturns an arrow function that remembers$m, andarray_mapuses it.array_filterkeeps the even numbers.
Expected result
cannot see it
11
3
15
12
123 1
2,4,6
2,4,6
In the real world
Closures are everywhere in modern PHP. Frameworks such as Laravel use them for routes and for collection methods like map and filter. Event systems call closures when something happens, and sorting uses a closure to decide which record comes first. Understanding scope also helps you read errors such as "undefined variable".
Common mistakes
- Using a global variable inside a function without passing it in.
- Forgetting
usein a normal closure, so the variable is undefined inside. - Expecting an arrow function to change an outer variable. It captures by value.
- Forgetting that a closure copies the value at creation time, so later changes to the outer variable are not seen.
Best practices
- Pass values as parameters instead of using
global. - Use arrow functions for short one-expression callbacks.
- Use
use (&$x)only when the closure must change the outer variable. - Use static variables for small private counters and caches.
Summary
Variables made inside a function are local, and a function sees global variables only through global or parameters. A static variable keeps its value between calls. A closure is a function stored in a variable; it needs use to see outer variables, and use (&$x) shares them. An arrow function fn captures by value and holds one expression.
Quick check
Key takeaways
- Functions have their own scope and do not see outside variables.
- A closure needs use to see outside variables, and an ampersand shares them.
- Arrow functions are short closures that capture automatically.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.