PHP Var Scope

Variable Scope and Static Variables

The scope of a variable refers to where the variable is accessible within your code. Understanding variable scope helps you manage data effectively and avoid conflicts.

Types of Variable Scope in PHP

1. Local Scope

  • Variables declared inside a function are local to that function.
  • They cannot be accessed outside the function.

Example:

<?php
function myFunction() {
    $localVar = "I am local!";
    echo $localVar;
}
myFunction(); // Outputs: I am local!
// echo $localVar; // Error: Undefined variable
?>

Try It Now

2. Global Scope

  • Variables declared outside of any function are global.
  • They cannot be accessed directly inside functions.
  • Use the global keyword to access global variables inside a function.

Example:

<?php
$globalVar = "I am global!";

function showGlobal() {
    global $globalVar; // Access the global variable
    echo $globalVar;
}
showGlobal(); // Outputs: I am global!
?>

Try It Now

3. Static Variables

  • A static variable keeps its value between function calls.
  • It is declared using the static keyword.
  • Unlike normal local variables, static variables retain their value instead of being reinitialized.

Example:

<?php
function countCalls() {
    static $counter = 0; // Retains value between calls
    $counter++;
    echo "Call count: $counter<br>";
}

countCalls(); // Outputs: Call count: 1
countCalls(); // Outputs: Call count: 2
countCalls(); // Outputs: Call count: 3
?>

Try It Now

4. Superglobals

  • PHP provides built-in variables called superglobals, which are accessible anywhere in the script.
  • Examples: $_POST, $_GET, $_SESSION, $_SERVER, etc.

Key Points

  1. Local Variables: Exist only inside a function.
  2. Global Variables: Declared outside functions and accessed using global inside functions.
  3. Static Variables: Retain their value between function calls.
  4. Superglobals: Always accessible and predefined by PHP.