Variable Scope: Local and Global
Understand how PHP isolates function scope and how to use the global keyword.
Variable Scope: Local and Global is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Variable Scope in PHP
In PHP every variable has a scope — the region of code where it is accessible.
- Variables created outside functions are in global scope
- Variables created inside functions are in local scope
- PHP does NOT have block scope (unlike C or JavaScript)
Local Scope
Variables inside a function are local — they disappear when the function returns:
<?php
function compute(): void {
$result = 42; // local variable
echo $result; // 42
}
compute();
echo $result ?? 'undefined'; // undefined — $result is goneGlobal Variables Are NOT Auto-Visible
Unlike many languages, PHP functions cannot see global variables by default — you must explicitly import them:
<?php
$message = 'Hello';
function printMessage(): void {
echo $message ?? 'not visible'; // 'not visible'
// $message from global scope is not accessible here
}The global Keyword
Use global $varName inside a function to access a global variable:
<?php
$counter = 0;
function increment(): void {
global $counter;
$counter++;
}
increment();
increment();
echo $counter; // 2$GLOBALS Superglobal
$GLOBALS is an array that holds all global variables — accessible anywhere without the global keyword:
<?php
$total = 100;
function addTax(): void {
$GLOBALS['total'] *= 1.18; // 18% tax
}
addTax();
echo $total; // 118Why Avoid global
Overusing global creates hidden dependencies — functions become hard to test and debug. Prefer passing values as arguments:
<?php
// Bad
$db = new PDO(/* ... */);
function getUsers(): array {
global $db;
return $db->query('SELECT * FROM users')->fetchAll();
}
// Good
function getUsers(PDO $db): array {
return $db->query('SELECT * FROM users')->fetchAll();
}Static Variables
A static variable retains its value between function calls but is still local to the function:
<?php
function callCount(): int {
static $count = 0;
return ++$count;
}
echo callCount(); // 1
echo callCount(); // 2
echo callCount(); // 3Closures and Variable Capture
Closures (anonymous functions) can capture outer variables with use:
<?php
$prefix = 'Mr';
$greet = function(string $name) use ($prefix): string {
return "$prefix. $name";
};
echo $greet('Smith'); // Mr. SmithCapture by Reference
Capture by reference with use (&$var) so the closure can modify the outer variable:
<?php
$total = 0;
$add = function(int $n) use (&$total): void {
$total += $n;
};
$add(10);
$add(5);
echo $total; // 15Arrow Functions
PHP 7.4 arrow functions (fn =>) automatically capture outer scope by value — no use needed:
<?php
$multiplier = 3;
$nums = [1, 2, 3, 4];
$result = array_map(fn($n) => $n * $multiplier, $nums);
print_r($result); // [3, 6, 9, 12]Nested Functions
PHP allows defining a function inside another, but the inner function becomes globally accessible after the outer is called:
<?php
function outer(): void {
function inner(): void {
echo 'inner called';
}
}
// inner(); // Fatal: undefined before outer() is called
outer();
inner(); // works nowQuick Check
What does a static variable inside a PHP function do?
Recap: Variable Scope
Key scope rules in PHP:
- Functions have their own local scope
- Global variables must be imported with
global - Use
$GLOBALS['name']as an alternative staticvariables persist across calls within a function- Closures capture outer vars with
use - Arrow functions auto-capture by value
Frequently asked questions
Is the “Variable Scope: Local and Global” lesson free?
Yes — the full text of “Variable Scope: Local and Global” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Variable Scope: Local and Global”?
Understand how PHP isolates function scope and how to use the global keyword. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Variable Scope: Local and Global” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining and Calling Functions
- Default and Variadic Parameters
- Variable Scope: Local and Global
- Anonymous Functions and Closures