19. Variable Scope: Local, Global, and Static
Variable scope determines where a variable can be accessed, read, and modified within a script.
1. Local Scope
Variables declared inside a function are local to that function and cannot be accessed from outside.
php
"; } testScope(); // echo $local_var; // ERROR: Undefined variable ?>2. Global Scope
Variables declared outside any function have global scope. They can be accessed globally, but not directly inside functions.
To access a global variable inside a function, you must use the global keyword or the special $GLOBALS array.
php
"; // Method B: using the $GLOBALS superglobal array $GLOBALS['global_message'] = "I was modified in the function."; echo "Global using GLOBALS: " . $GLOBALS['global_message'] . ""; } accessGlobal(); echo "Outside function after modification: " . $global_message; ?>
3. Static Scope
Variables declared with the static keyword inside a function retain their last value between multiple calls to that function, instead of being destroyed after the function finishes.
php
"; } counter(); // 1 counter(); // 2 counter(); // 3 ?>