Variable Scope in PHP
As your PHP code grows, understanding how variables behave across different parts of your application becomes critical. Many beginner bugs come not from syntax errors, but from misunderstanding where a variable is accessible.
In this lesson, you’ll learn about variable scope in PHP and essential code practices that help you write clean, maintainable, and bug-free code.
What is Variable Scope?
Variable scope defines where a variable can be accessed in your code. In PHP, variables do not automatically exist everywhere — their visibility depends on where they are defined.
Local Scope
A variable declared inside a function is only accessible within that function.
Example
function test() {
$message = "Hello";
echo $message;
}
test();
Output:
Hello
Outside Access (Fails)
function test() {
$message = "Hello";
}
test();
echo $message;
Why it fails:
Variables inside functions cannot be accessed outside.
Global Scope
A variable declared outside a function is not automatically available inside it.
Example (Fails)
$name = "Rohan";
function greet() {
echo $name;
}
greet();
Fix using global
$name = "Rohan";
function greet() {
global $name;
echo $name;
}
greet();
Output:
Rohan
Alternative: $GLOBALS
$name = "Rohan";
function greet() {
echo $GLOBALS['name'];
}
greet();
Note:
$GLOBALS is useful when you need to access a global variable dynamically by name, but for most cases global is cleaner and more readable.
Static Variables (Important Concept)
A static variable inside a function retains its value between function calls.
Example
function counter() {
static $count = 0;
$count++;
echo $count . " ";
}
counter();
counter();
counter();
Output:
1 2 3
Why this matters:
Unlike normal variables, static variables do not reset every time the function runs. They are useful for counters, caching, and tracking state without using global variables.
Best Practices for Using Variables
1. Avoid Excessive Use of global
Using too many global variables makes code harder to debug and maintain.
Better approach:
function greet($name) {
return "Hello " . $name;
}
echo greet("Rohan");
2. Use Meaningful Variable Names
Bad:
$x = 10;
Good:
$totalPrice = 10;
Why it matters:
Readable code is easier to maintain and debug.
3. Keep Functions Focused (Single Responsibility)
Bad:
function processOrder($price) {
$discount = $price * 0.1;
$final = $price - $discount;
mail("user@example.com", "Order", "Placed");
file_put_contents("log.txt", "Order processed");
return $final;
}
Good:
function calculateDiscount($price) {
return $price * 0.1;
}
function logOrder() {
file_put_contents("log.txt", "Order processed");
}
Why it matters:
Each function should handle one responsibility only.
4. Avoid Magic Values
Bad:
$total = $price + 18;
Good:
$tax = 18; $total = $price + $tax;
5. Consistent Naming Style
$userName = "Rohan"; $totalAmount = 100;
Common Mistakes Beginners Make
1. Expecting Global Variables Inside Functions
$count = 5;
function test() {
echo $count;
}
Why it fails:
Global variables are not accessible unless explicitly declared.
2. Overusing Global Variables
global $a, $b, $c;
Why it’s bad:
Creates tightly coupled and hard-to-maintain code.
3. Using Generic Variable Names
$data = "Rohan"; $data = 100;
Why it’s confusing:
Generic names like $data, $value, or $temp make it hard to understand what the variable represents.
Real-World Example (Scope in Action)
function visitCounter() {
static $count = 0;
$count++;
return $count;
}
echo visitCounter(); // 1
echo visitCounter(); // 2
echo visitCounter(); // 3
Output:
123
What this shows:
- Static variable retains value
- No global variables needed
- Clean, predictable behavior
Practice Exercise
Task 1
Create a variable inside a function and check if it exists outside using isset().
Expected Output:
Variable not accessible
Task 2
Use global keyword to access a variable inside a function.
Expected Output:
Rohan
Task 3
Create a function that uses a static variable to count how many times it is called.
Expected Output:
1 2 3
Summary
In this lesson, you learned how variable scope works in PHP, including local, global, and static scope. You also explored best coding practices that help you write clean, readable, and maintainable code.
Understanding scope is essential for avoiding bugs and building scalable applications.