0Pricing
PHP Academy · Lesson

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 gone

All lessons in this course

  1. Defining and Calling Functions
  2. Default and Variadic Parameters
  3. Variable Scope: Local and Global
  4. Anonymous Functions and Closures
← Back to PHP Academy