Variable Scope
Learn how local, global, and static scope control where a variable can be seen and used inside a PHP script.
Introduction
Now that you can write your own functions, a natural question comes up: if I create a variable inside a function, can I use it outside that function? And if I create a variable outside a function, can the function see it? The answer to both, by default, is no — and that behavior is called variable scope.
Understanding scope is essential for writing functions that behave predictably. Without it, you will eventually run into confusing bugs where a variable seems to "disappear" or a function seems to ignore a value you set earlier in the script.
- What "scope" means and why PHP separates local and global scope.
- How local scope keeps a function's variables private to itself.
- How to use the global keyword to access a global variable inside a function.
- How static variables remember their value between function calls.
- Why relying on global state is generally considered bad practice.
What is Variable Scope?
Scope refers to the part of a script where a variable is visible and can be used. PHP has a few different scopes, but the two you will run into constantly are local scope (inside a function) and global scope (outside every function, at the top level of the script).
By default, a function in PHP cannot see variables defined outside it, and code outside a function cannot see variables defined inside it. Each function gets its own private set of variables, completely separate from the rest of the script.
Think of every function as running inside its own sealed room. Variables created inside the room stay in the room. Variables created outside the room are invisible from inside it — unless you explicitly let them in.
Local Scope
A variable declared inside a function has local scope: it only exists while that function is running, and it cannot be accessed from outside the function. Once the function finishes executing, the variable is destroyed.
<?php
function greet() {
$message = "Hello from inside the function!";
echo $message . "\n";
}
greet();
echo $message; // Error: undefined variable $message
?>Hello from inside the function!
Warning: Undefined variable $messageThe $message variable only lives inside greet(). Trying to echo it outside the function fails because, from the outside world's point of view, that variable was never created.
This isolation is a feature, not a limitation. It means you can reuse the same variable name in different functions without them interfering with each other.
<?php
function calculateTotal() {
$result = 10 + 20;
echo "Total: $result\n";
}
function calculateAverage() {
$result = (10 + 20) / 2;
echo "Average: $result\n";
}
calculateTotal();
calculateAverage();
?>Total: 30
Average: 15Both functions use a variable named $result, but each one is a completely separate variable that only exists within its own function.
Global Scope
A variable declared outside of any function — directly in the main body of the script — has global scope. It is visible to any regular script code at that same top level, but functions still cannot see it automatically.
<?php
$siteName = "PrograMinds";
echo "Welcome to " . $siteName . "\n"; // Works fine, top-level code
function showSiteName() {
echo "Welcome to " . $siteName . "\n"; // Undefined - function can't see it
}
showSiteName();
?>Welcome to PrograMinds
Warning: Undefined variable $siteNameMany beginners expect a global variable to automatically be visible inside every function, since that is how some other languages behave. In PHP, functions are isolated by default, and you must explicitly opt in to see a global variable.
The global Keyword
If a function genuinely needs to read or modify a variable defined in the global scope, PHP provides the global keyword. Declaring global $variableName; inside a function links that name to the global variable of the same name.
<?php
$siteName = "PrograMinds";
function showSiteName() {
global $siteName;
echo "Welcome to " . $siteName . "\n";
}
showSiteName();
?>Welcome to PrograMindsThe global keyword does not copy the value — it creates a reference to the actual global variable. That means changes made inside the function affect the global variable too.
<?php
$counter = 0;
function increment() {
global $counter;
$counter++;
}
increment();
increment();
increment();
echo "Counter is now: " . $counter . "\n";
?>Counter is now: 3PHP also exposes global variables through a special array called $GLOBALS, which you can use as an alternative to the global keyword.
<?php
$siteName = "PrograMinds";
function showSiteNameAlt() {
echo "Welcome to " . $GLOBALS["siteName"] . "\n";
}
showSiteNameAlt();
?>Welcome to PrograMindsStatic Variables
Normally, a local variable is recreated from scratch every time its function runs, and it loses its value the moment the function ends. Sometimes, though, you want a function to remember a value between calls — for example, to count how many times it has been called. That is what the static keyword is for.
<?php
function trackCalls() {
static $count = 0;
$count++;
echo "This function has been called $count time(s).\n";
}
trackCalls();
trackCalls();
trackCalls();
?>This function has been called 1 time(s).
This function has been called 2 time(s).
This function has been called 3 time(s).The static $count = 0; line only initializes $count to 0 the very first time the function runs. On every later call, PHP skips the initialization and reuses whatever value $count held at the end of the previous call.
A static variable is still local to its function — no other function or outside code can access it directly. It just persists across calls to that one function, unlike global variables which are shared and accessible everywhere they are declared.
Why Global State Is Discouraged
It might seem convenient to make every variable global so any function can use it. In practice, this tends to create fragile code as a project grows.
Problems With Relying on Globals
- Any function can silently change a global variable, making bugs hard to trace back to their source.
- Functions become harder to test and reuse, since they secretly depend on outside state instead of their own parameters.
- Two different parts of a large codebase can accidentally use the same global variable name and interfere with each other.
- Code that depends on globals is harder to reason about, because you cannot tell what a function does just by looking at its parameters.
The generally preferred approach is to pass data into functions as parameters and get data back out using return values, rather than reaching into global variables. This keeps each function self-contained and predictable.
<?php
// Less ideal: relies on global state
$taxRate = 0.08;
function calculateTotalGlobal($price) {
global $taxRate;
return $price + ($price * $taxRate);
}
// Better: explicit parameter, no hidden dependency
function calculateTotal($price, $taxRate) {
return $price + ($price * $taxRate);
}
echo calculateTotal(100, 0.08) . "\n";
?>108Common Mistakes
- Expecting a function to automatically see variables from outside it without using global or $GLOBALS.
- Forgetting that a static variable keeps its value between calls, and being surprised when it does not reset.
- Overusing the global keyword instead of passing values through parameters and return values.
- Assuming a variable inside a function still exists after the function has finished running.
Best Practices
- Prefer passing values as parameters and getting results back with return statements over using global.
- Reserve static variables for genuine per-function memory, like counters or caches, not as a substitute for proper design.
- Keep global variables to an absolute minimum, especially in larger applications.
- Give variables clear, specific names so accidental name collisions between functions are less likely.
Frequently Asked Questions
Can two functions have a local variable with the exact same name?
Yes. Because each function has its own local scope, the two variables are completely independent even though they share a name.
Does the global keyword copy the variable's value into the function?
No. It links the local name to the actual global variable, so changes made inside the function affect the original global variable.
What happens to a static variable if I never call its function?
Nothing — it is only initialized the first time the function actually runs. If the function is never called, the static variable is never created.
Is $GLOBALS the same thing as using the global keyword?
They achieve the same result — accessing a global variable inside a function — but $GLOBALS is an associative array you can access anywhere, while global creates a local reference by name.
Why is avoiding global state considered good practice in other languages too?
This is not unique to PHP — most programming languages discourage heavy reliance on global state because it makes code harder to test, debug, and reason about.
Key Takeaways
- Local scope means a variable declared inside a function only exists within that function.
- Global scope means a variable declared outside any function lives at the top level of the script.
- Functions cannot see global variables automatically — use the global keyword or $GLOBALS to access them.
- The static keyword lets a local variable retain its value between successive calls to the same function.
- Relying heavily on global state is generally discouraged in favor of passing data through parameters and return values.
Summary
Variable scope determines where in your script a variable can be seen and used. Local variables stay locked inside their function, global variables live at the top level, and static variables give a function memory across calls.
In this lesson, you learned how PHP isolates function variables by default, how to deliberately reach into global scope with the global keyword, and why leaning on global state is usually a design smell. Next, you will learn how to split your PHP code across multiple files using include and require.
- You understand the difference between local and global scope.
- You can use the global keyword to access a global variable inside a function.
- You know how static variables persist their value between function calls.
- You understand why minimizing global state leads to more maintainable code.