Variable Scope: Local and Global
Understand how PHP isolates function scope and how to use the global keyword.
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 goneAll lessons in this course
- Defining and Calling Functions
- Default and Variadic Parameters
- Variable Scope: Local and Global
- Anonymous Functions and Closures