Back to results for “Scope”
PHP › Functions & Scope

What is variable scope in PHP, and why can't a function normally access a variable defined outside of it?

Beginner

Answer

Variable scope determines where in your code a particular variable can be accessed, and in PHP, a variable defined inside a function is local to that function by default and cannot be accessed from outside it, while a variable defined outside any function exists in the global scope but is also not automatically accessible from within a function unless explicitly imported using the global keyword, a design intended to prevent functions from accidentally interfering with unrelated parts of a program.
$total = 100;
function showTotal() {
    echo $total ?? 'not accessible here';
}
showTotal();
Real-world example A developer troubleshooting an undefined variable warning realizes their function was trying to directly use a variable defined outside of it, and fixes the issue by properly passing that value into the function as a parameter instead.

Common follow-ups: Why does PHP intentionally isolate function scope from the global scope by default?;What is the difference between using the global keyword and simply passing a variable as a parameter?