Course Content
About Lesson

Variable scope (global, local, static)

In PHP, the scope of a variable determines where you can access or use that variable in your program. There are mainly 3 types of variable scope in PHP:

  1. Local Scope
  2. Global Scope
  3. Static Scope
  • A variable declared inside a function is local to that function.
  • You cannot access it outside the function.
PHP
<?php
function testLocal() {
    $x = 10; // Local variable
    echo "Inside function: x = $x <br>";
}

testLocal();
echo "Outside function: x = $x"; // Error: x not defined outside
?>

Explanation:

  • $x only exists inside the function.
  • Output:
    • Inside function: x = 10
    • Outside function: x =
  • A variable declared outside a function has global scope.
  • To access it inside a function, you must use the global keyword.
PHP
<?php
$x = 20; // Global variable

function testGlobal() {
    global $x;  // Import global variable into function
    echo "Inside function: x = $x <br>";
}

testGlobal();
echo "Outside function: x = $x <br>";
?>

Explanation:

  • Without the global keyword, $x inside the function would not work.
  • Output:
    • Inside function: x = 20
    • Outside function: x = 20
  • PHP offers a unique superglobal array named $GLOBALS[] that allows access to global variables within functions.
PHP
<?php
$a = 5;
$b = 10;

function sum() {
    $GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}

sum();
echo "The sum is: " . $c;
?>

Explanation:

  • Output: The sum is: 15
  • Normally, when a function ends, local variables are destroyed.
  • If you declare a variable as static, it will keep its value between function calls.
PHP
<?php
function counter() {
    static $count = 0; // Static variable
    $count++;
    echo "Count = $count <br>";
}

counter();
counter();
counter();
?>

Explanation:

  • Output:
    • Count = 1
    • Count = 2
    • Count = 3